在这种情况下,我的代码结构如下:
Thing.prototype = {
doSomething: function() {
$(selector).click(this.handleClick.bind(null, this));
},
handleClick: function(self, event) {
console.log(this); //Window
console.log(self); //Thing
}
}
如何绑定(bind)这个东西 this
self
的上下文参数并仍然保留 this
的行为对象就像没有使用 bind
绑定(bind)参数一样方法?
注意:我知道我可以绑定(bind) this
并使用e.originalEvent.target
得到我想要的行为,但我只是好奇是否还有其他方法
我希望我能够实现我想要实现的目标,如果有任何不明确的地方,请发表评论。
最佳答案
How could one bind the Thing this context to the self argument and still keep the behavior of the this object as if no arguments were bound using the bind method?
您不会为此使用bind
,因为您希望this
是动态的。相反:
doSomething: function() {
var self = this;
$(selector).click(function(e) {
return self.handleClick.call(this, self, e);
});
},
在 handleClick
期间,this
将引用被单击的元素,第一个参数将是 Thing
实例,第二个参数将是是事件:
handleClick: function(self, event) {
console.log(this); // The clicked element
console.log(self); // The Thing
console.log(event); // The event
}
关于javascript - 将此参数绑定(bind)到命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29943717/