从js类分配事件侦听器

Assign event listener from js class

本文关键字:事件 侦听器 分配 js      更新时间:2023-09-26

我想将onclick事件侦听器分配给类中的对象然后从创建onclick 的实例中获取一些变量

function myclass() {
    this.myvar;
    this.myfunc = function() 
    {
        alert(this.myvar);
        document.onmousedown = this.mouseDown;        
    }
    this.mouseDown = function(e) 
    {
        alert(this.myvar); //does not work of course
        //how could I access myvar from current myclass instance
    }
}

var myclass_instance = new myclass();
    myclass_instance.myvar = 'value'
    myclass_instance.myfunc();

http://jsfiddle.net/E7wK4/

mouseDown事件中的this不是实例的this

请尝试

function myclass() {
    var _this = this;
    this.myvar;
    this.myfunc = function() 
    {
        alert(this.myvar);
        document.onmousedown = this.mouseDown;        
    }
    this.mouseDown = function(e) 
    {
        alert(_this.myvar); //<<<<
    }
}

演示:http://jsfiddle.net/maniator/E7wK4/1/

作为@Neal的替代方案,您可以绑定它。

document.onmousedown = this.mouseDown.bind(this);