Mootools class variable scope

烂漫一生 提交于 2019-12-10 10:43:28

问题


Take this class:

var MyClass = new Class({
    Implements: [Events, Options],
    initialize: function() {

        this.a = 1;

    },

    myMethod: function() {

        var mc = new differentClass({
            events: {
                onClick: function() {

                    console.log(this.a); // undefined (should be 1, 2, 3 etc)

                    this.a ++;


                }
            }
        });    

    }
});

How do I keep the value of this.a? I am basically trying to draw a line (using canvas) from the last point to the co-ordinates just clicked.

[EDIT]

I dont want to bind this as it's bad apparently and it will over-ride the differentClass options.


回答1:


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




回答2:


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 ++;
            }
        }
    });    
}
...


来源:https://stackoverflow.com/questions/10385560/mootools-class-variable-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!