gpt4 book ai didi

javascript - 混淆javascript绑定(bind)函数

转载 作者:行者123 更新时间:2023-11-29 16:15:08 27 4
gpt4 key购买 nike

我运行下面的 JS 脚本,但只发现 func2() 输出是 foobar,而不是 George,谁能解释为什么 func2 = func.bind(someuser) 没有将 someuser 绑定(bind)到 func 吗?

var someuser = {
name: 'George',
func: function () {
console.log(this.name);
}
};
var foo = {
name: 'foobar'
};
func = someuser.func.bind(foo);
func(); // output foobar
func2 = func.bind(someuser);
func2(); //output foobar

最佳答案

来自 MDN :

The bind() function creates a new function (a bound function) with the same function body (internal Call attribute in ECMAScript 5 terms) as the function it is being called on (the bound function's target function) with the this value bound to the first argument of bind(), which cannot be overridden.

基本上这意味着您不能在已绑定(bind)的函数上调用绑定(bind)。

在您的示例中,您必须执行以下操作:

func2 = someuser.func.bind(someuser);

关于javascript - 混淆javascript绑定(bind)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17668099/

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