我是 Javascript OOP 的新手,对绑定(bind)到事件处理程序中的回调有疑问。
我试图在我的构造函数中将事件处理程序应用于 DOM 元素。事件处理函数是对象的一个方法,我试图将回调函数(也是同一对象的一个方法)传递给该处理函数。
当我在处理程序中硬编码回调(使用 this.callbackMethod())时,它按预期运行:
class Foo {
constructor (name){
this.name = name
this.bar();
}
callback(){
console.log(this.name + 'bar callback this:') // 'foobar callback this:
console.log(this) // Foo object with name 'foo'
}
bar(){
document.querySelector('button').addEventListener('click', function(){
console.log('bar click event this:')
console.log(this)
// this is the relevant line
this.callback()
}.bind(this));
}
}
const foo = new Foo('foo');
但是,当我将该参数作为回调传递时,即使我在回调和处理程序上都使用 .bind(this),它也会失败:
class Foo {
constructor (name){
this.name = name
this.bar(this.callback);
}
callback(){
console.log(this.name + 'bar callback this:')// Uncaught TypeError: Cannot read property 'name' of undefined
console.log(this)
}
bar(cb){
document.querySelector('button').addEventListener('click', function(){
console.log(cb)// logs function definition
// this is the relevant line
cb().bind(this);
}.bind(this));
}
}
const foo = new Foo('foo');
代码笔示例:
硬编码回调:https://codepen.io/RandomNeuralFiring/pen/Pgrdey
参数回调:https://codepen.io/RandomNeuralFiring/pen/QPXVOR
我想要重新使用 bar() 和其他回调的选项,所以很想了解如何动态设置它的上下文。
附言我找不到适合对象绑定(bind)的标签 - 也许应该创建一个?
最佳答案
您正在绑定(bind)
cb
的返回值 - 尝试先绑定(bind)函数然后调用它:
cb.bind(this)();
关于javascript - 当作为参数传递时,对象方法回调会丢失其在事件处理程序中的绑定(bind),但在硬编码时不会,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55945915/