Overwritten “this” variable problem or how to call a member function?

前端 未结 4 1259
小鲜肉
小鲜肉 2020-12-21 23:16

I have this class where I am using a combination of jQuery and Prototype:

var MyClass = Class.create({
    initElements: function(sumEl) {
       this.sumEl          


        
4条回答
  •  执笔经年
    2020-12-21 23:38

    DOMEvent handlers are traditionally called with the elements they're registered to as context / "this". This is what jQuery does, too.

    The easiest option for you would be to use jQuery's ability to handle event data

    var MyClass = Class.create({
     initElements: function(sumEl) {
            this.sumEl = sumEl;
            sumEl.bind("keyup", this, this.updateSumHandler);
     },
    
     updateSumHandler: function(event) {
        // event.data is the initial this
    
        // call updateSum with correct context
        event.data.updateSum.call(event.data);
     },
    
     updateSum: function() {
            // does something here
     }
    });
    

    The other possibility is to use closures to define the updateHandler inside the constructor

    var MyClass = Class.create({
     initElements: function(sumEl) {
            this.sumEl = sumEl;
    
            // save this as that so we can access it from the anonymous function
            var that = this;
            sumEl.keyup(function()
            {
               that.updateSum();
            });
     },
    
     updateSum: function() {
            // does something here
     }
    });
    

    This is a working example what one of the other answers tried to do. It works because the anonymous function can always access the variables in the surrounding function -- but it only works if the function is really defined in the function that has "that" as local variable.

提交回复
热议问题