Mootools class variable scope

瘦欲@ 提交于 2019-12-06 09:31:01

several patterns are available.

decorator via .bind()

var mc = new differentClass({
    events: {
        click: function() {
             console.log(this.a);
             this.a ++;
        }.bind(this) // binds the scope of the function to the upper scope (myclass)
    }
});    

keeping a reference.

var self = this; // reference parent instance of myClass
var mc = new differentClass({
    events: {
        click: function() {
             console.log(self.a); 
             self.a ++;
        }
    }
});    

pointing to a myClass method that can deal with it:

handleClick: function() {
    this.a++;
},
myMethod: function() {
    var mc = new differentClass({
        events: {
            click: this.handleClick.bind(this)
        }
    });    
}

the 2-nd one - by storing a reference is preferred due to the smaller footprint and universal support whereas .bind is not available in every browser and needs to be shimmed as well as the extra time to curry the function on execution.

self is what you will find in mootools-core itself when possible.

if performance is not at risk, method 3 can probably offer the best readability and code structure. the arguments to the method will remain what the click handler passes, i.e. event and event.target will be the handler.

in pattern #2 with self, this will point to the click handler within the anonymous function (or to the other class, for example), which may be useful as well - rebinding context can be a pain in the neck

You can refer proper context like this:

...
myMethod: function() {
    var _this = this;
    var mc = new differentClass({
        events: {
            onClick: function() {
                console.log(_this.a);
                _this.a ++;
            }
        }
    });    
}
...
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!