gpt4 book ai didi

javascript - 将方法名称作为回调传递 VS。用匿名函数包装它

转载 作者:行者123 更新时间:2023-11-30 17:58:49 25 4
gpt4 key购买 nike

我有一个按钮#test。

var obj = {
name: "John",
test: function() {
console.log('name '+ this.name );
}
};

$("#test").on( "click", obj.test);

这将记录一个空字符串(logging typeof this.name 给出一个字符串)。

编辑:我理解 this 上下文成为按钮,因此 this.name 不返回任何内容。

对比

var obj = {
name: "John",
test: function() {
console.log('name '+ this.name );
}
};

$("#test").on( "click", function() {
obj.test(); //logs John
});

有什么区别?

编辑:用 annon 函数包装 obj.test() 如何使其行为与上面不同?

最佳答案

这是关于解决this。如果您使用 $("#test").on("click", obj.test); 然后 this 将成为按钮,但如果您传递 closure那么 this 将是 obj

当我调用 obj.test 时,测试中的 this 将是 obj。

JQuery 会将 this 设置为单击时的按钮,因此传递 obj.test 而不引用 obj 是 this 将破坏您的 obj.test 功能。

解决此问题的最佳方法是使用 Function.prototype.bind (对于 IE < 9,您需要 polyfil):

var obj = {
name: "John",
test: function () {
console.log('This is:' + this.toString());
},
toString: function () {
return "It's test"
}
};

$("#test").on("click", function () {
// by the way; this here is the button
console.log("what's this here:", this.toString());
obj.test(); //works but creates a closure
});

$("#test").on("click", obj.test);//breaks, this will be button in test

$("#test").on("click", obj.test.bind(obj));//works

// now to show how this is resolved
window.mytest = obj.test;
window.mytest();// this is window
var obj2 = {
toString: function () {
return "this is obj2";
}
};
obj2.test = obj.test;
obj2.test();//this is obj2

关于javascript - 将方法名称作为回调传递 VS。用匿名函数包装它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17538404/

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