Created
December 7, 2017 12:40
-
-
Save fatso83/b7e42698fc44f4c9a5b4c7dc859da4b9 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class A { | |
constructor(arg1, arg2, argn){ | |
console.log('A', typeof this.check) | |
this.arg = arg1; | |
this.bar = this.foo; | |
} | |
check(){ | |
console.log('this.foo',this.foo) | |
console.log('this.args', this.arguments) | |
} | |
} | |
// @see https://github.com/ProLoser/sinon/blob/3526a6b63986c50a34a8d160cd7b21e6de9129b1/lib/sinon/spy.js#L198 | |
function callConstructorWithPresetThis (func, thisValue, args){ | |
// new a constructor `func` with `this` set to `thisValue` and args from `args | |
// like new func.bind(thisValue, arg1, arg2, ...) | |
// which is almost like `new func(arg1, arg2, ..)` - only with `thisValue` bound | |
var ret = new (Function.prototype.bind.apply(func, [thisValue].concat(args))) | |
return ret; | |
} | |
class B{} | |
var obj1 = Object.create(B.prototype); | |
var obj2 = Object.create(B.prototype); | |
obj1.foo = 'obj1'; | |
obj2.foo = 'obj2'; | |
var ret1 = callConstructorWithPresetThis(A, obj1, [1, 2]) | |
console.log('ret', ret1); | |
console.log(ret1.arg) | |
console.log('thisValue', obj1); | |
var ret2 = callConstructorWithPresetThis(A, obj2, [10, 20, 30, 40]) | |
console.log('ret', ret2); | |
console.log(ret2.arg) | |
console.log('thisValue', obj2); | |
console.log( | |
'is of A', | |
obj1 instanceof A, | |
obj2 instanceof A, | |
ret1 instanceof A, | |
ret2 instanceof A, | |
) | |
console.log( | |
'is of B', | |
obj1 instanceof B, | |
obj2 instanceof B, | |
ret1 instanceof B, | |
ret2 instanceof B, | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment