gpt4 book ai didi

javascript - 如何在绑定(bind)函数上强制使用不同的指针

转载 作者:行者123 更新时间:2023-11-29 16:35:03 25 4
gpt4 key购买 nike

我对 bindapply 的工作原理感到困惑。

我知道bind将指针绑定(bind)到函数,并且apply告诉函数使用调用时给定的指针运行,所以我做了一些测试并使用apply 指针,但它没有任何效果,它仍然使用 bind 指针。

如何强制函数使用不同的指针而不绑定(bind)永久的新指针?

这是我的测试:

预期输出:
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));

最佳答案

this绑定(bind)到 .bind 的函数引用不能通过传递不同的 this 来覆盖至.apply .

想想.bind像这样工作(但忽略真实版本还附加额外预设功能参数的能力):

function bind(fn, ctx) {
return function(...args) {
return fn.apply(ctx, args);
}
}

let boundFunc = bind(myfunc, myctx);
boundFunc.apply(newctx, arg1, arg2);

您应该能够看到 newctx 没有办法传递至myfunc通过boundFunc因为最里面的调用是.apply在封口里面bind()确定传递的上下文(即提供给 bind 的上下文)。

关于javascript - 如何在绑定(bind)函数上强制使用不同的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52061844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com