【问题标题】:Javascript Class, var undefined in event listener [duplicate]Javascript类,事件侦听器中未定义的变量[重复]
【发布时间】:2014-10-28 09:45:39
【问题描述】:
var Foo = (function(){

    function Foo(){
        this._s="string";
        this.setButton();
    };

    Foo.prototype.setButton = function(){
document.getElementById('id').addEventListener('click', function(event) {
        alert(this._s);
    });
};

    Foo.prototype.method = function(){
        alert(this._s);
    }; 

    return Foo;

})();

var fo = new Foo();
fo.method();

我想将一个事件绑定到一个按钮,并执行一个使用“私有”变量的函数,当我单击该按钮时,该函数被正确调用但它看不到变量 this._s(它写“不明确的')。如果我写 fo.method() 字符串会正确打印。 这是jsfiddle:http://jsfiddle.net/wLm1v4La/1/

【问题讨论】:

  • 在事件处理程序内部,this 是另一个this
  • 简易解决方案here

标签: javascript class oop


【解决方案1】:

你必须在传递它之前手动设置函数的上下文(this)。

 Foo.prototype.setButton = function () {
   var tmpFunc = function(evt){ alert(this._s); } //store the function
   var boundFunction = tmpFunc.bind(this); //set the context manually
   //pass the function now to eventlistener
   document.getElementById('id').addEventListener('click',boundFunction);
 };

【讨论】:

  • 您的解决方案有效,'this' is Javascript is very tricky.
  • 它不是指全局对象(窗口),尝试使用alert(this);,它会显示按钮元素。我相信默认是this 指的是事件注册到的元素
猜你喜欢
  • 1970-01-01
  • 2011-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多