【发布时间】:2016-04-17 01:52:36
【问题描述】:
在对象原型中存储的事件处理程序中保留this javascript 引用的正确方法是什么?我想远离创建像'_this'或'that'这样的临时变量,我不能使用像jQuery这样的框架。我看到很多人谈论使用“绑定”功能,但不确定如何在我的给定场景中实现它。
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'
};
【问题讨论】:
标签: javascript oop event-handling this