如何使用"this"获取事件处理程序中的类变量



这里有一些代码:

var class = function(elem,div){
    this.elem= elem;
    this.div = div;
    this.init = function(){
        this.div.bind('keyup',this.handler);
    }
    this.handler= function(event){
        //HOW DO I GET "this.elem" ???
        //here, this = div
    }
    this.init();
}

我想从我的"handler"函数中获取变量"elem",但每次我调用this.elem时,"this"指的是绑定到事件处理程序的elem!!。

好吧,您可以只引用elem

或者,您可以在处理程序之外声明var that = this;,然后引用that.elem

如果您对使用ES5很感兴趣,则可能需要调用Function.prototype.bind方法。像

this.handler= function(event){
    //HOW DO I GET "this.elem" ???
    //here, this = div
}.bind(this)

这种方法也有很多垫片,可以优雅地支持旧的浏览器。上面的代码会导致存储在this.handler中的函数在像new class();一样永远调用该方法时绑定到this的值。

我怀疑您正在将this.handler注册为事件处理程序本身。在这种情况下,该方法不是在对象的上下文中执行的;它和其他事件处理程序一样被执行。

尝试编写一个简单的处理程序,在类的实例上调用handler方法。

var instance = new class(...); // populate args that make sense 
document.yourElement.onclick = function(){
   instance.handler();
}

此外,您确实应该使用原型来定义实例方法。按照你现在的方式做是非常低效的。

var class = function(elem,div){
    this.elem= elem;
    this.div = div;
    this.init();
}

class.prototype.init = function(){
        this.div.bind('keyup',this.handler);
    }
class.prototype.handler= function(event){
        //HOW DO I GET "this.elem" ???
        //here, this = div
    }

elem在闭包中捕获,只需将其引用为elem:

this.handler= function (event) {
     //HOW DO I GET "this.elem" ???
     //here,
     elem; // elem from the constructor.
     this = div
} 

还有

  1. javascript中没有类。

  2. class是一个保留字,不应将其用作标识符名称。

  3. 根据您的名称和使用方式,我猜elem是DOM元素,div则是div元素。如果是这样,则它们没有绑定方法。如果你想分配一个监听器,那么:

    this.onkeyup = this.handler;
    

但它必须放在定义this.handler之后。

最新更新