在这种情况下,我的代码结构如下:
Thing.prototype = {
doSomething: function() {
$(selector).click(this.handleClick.bind(null, this));
},
handleClick: function(self, event) {
console.log(this); //Window
console.log(self); //Thing
}
}
如何将Thingthis
上下文绑定到self
参数并仍然保持this
对象的行为,就像没有使用bind
方法绑定任何参数一样?
注意:我知道我可以绑定this
并使用它e.originalEvent.target
来获取我想要的行为,但是我只是想知道是否还有其他方法
我希望我能完成我想实现的目标,如果有歧义,请发表评论。
如何将Thing此上下文绑定到self参数,并且仍然保持此对象的行为,就像没有使用bind方法绑定任何参数一样?
您不会为此而用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
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句