How to force a different pointer on a bonded function
How to force a different pointer on a bonded function
I am confused about how bind and apply work.
bind
apply
I know bind binds a pointer to a function and apply tell the function to run with the pointer given at the call time, so I did a little test and used the apply pointer but it didn't have any effects, it still uses the bind pointer.
bind
apply
apply
bind
How can I force the function to use a different pointer without bind a permanent new pointer?
Here is my test:
expected output:this.test is not a function
this.test
class A
test()
printA()
this.test();
console.log('A');
const dummy = function(func)
func.apply(this, );
;
const a = new A();
dummy(a.printA.bind(a));
1 Answer
1
The this bound to a function reference with .bind cannot be overridden by passing a different this to .apply.
this
.bind
this
.apply
Think of .bind as working like this (but ignoring the ability of the real version to also attach extra preset function parameters):
.bind
function bind(fn, ctx)
return function(...args)
return fn.apply(ctx, args);
let boundFunc = bind(myfunc, myctx);
boundFunc.apply(newctx, arg1, arg2);
You should be able to see that there's no way for newctx to be passed to myfunc via boundFunc because the innermost call to .apply in the closure inside bind() determines the passed context (i.e. the one supplied to bind).
newctx
myfunc
boundFunc
.apply
bind()
bind
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
I was to answer mostly the same thing than your edit. you were faster.
– Félix Brunet
Aug 28 at 16:05