本文介绍了在javascript原型事件处理程序中保留'this'引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在对象原型中存储的事件处理程序中保留此
javascript引用的正确方法是什么?我想远离创建像'_this'或'that'这样的临时变量,我不能使用像jQuery这样的框架。我看到很多人谈论使用'绑定'功能但不确定如何在我给定的场景中实现它。
What is the correct way to preserve a this
javascript reference in an event handler stored inside the object's prototype? I'd like to stay away from creating temp vars like '_this' or 'that' and I can't use a framework like jQuery. I saw a lot of people talk about using a 'bind' function but was unsure of how to implement it in my given scenario.
var Example = function(foo,bar){
this.foo = foo;
this.bar = bar;
};
Example.prototype.SetEvent = function(){
this.bar.onclick = this.ClickEvent;
};
Example.prototype.ClickEvent = function(){
console.log(this.foo); // logs undefined because 'this' is really 'this.bar'
};
推荐答案
我找到 bind()
到目前为止是最干净的解决方案:
I find bind()
being the cleanest solution so far:
this.bar.onclick = this.ClickEvent.bind(this);
BTW 其他 此$ c按惯例,$ c>经常被称为
BTW the other this
is called that
by convention very often.
这篇关于在javascript原型事件处理程序中保留'this'引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!