简体   繁体   中英

Set variable and pass to function or re-set variable?

Which is best? Set a variable and pass it into the call, or set the var again every time. I want self = this (ie the Slider obj) for consistency.

EDIT for answers: I know I can use this but I work with other team members and have agreed for consistency to use self when referencing the object at all times.

So is this better:

Slider = {
    init: function() {
        var self = this,
        foo = $('.someElement');

        self.bindEvent(self);
    },

    bindEvent: function(self) {
        self.foo.on('click', self.wasClicked(self));
    },

    wasClicked: function(e, self) {
        e.doSomething();
        self.done();
    }
};

Or this:

Slider = {
    init: function() {
        var self = this,
        foo = $('.someElement');

        self.bindEvent();
    },

    bindEvent: function() {
        var self = this;
        self.foo.on('click', self.wasClicked);
    },

    wasClicked: function(e) {
        var self = Slider;
        e.doSomething();
        self.done();
    }
};

Your code is more reusable if you utilize an argument for your binding target, as per your first example. For instance:

bindEvent: function(target) {
    target.onclick = function() { alert(target + " was clicked"); };
}

bindEvent() can now be called by other functions, and target something other than self . While in your current Slider object it only needs to be called by init() , in the future you may end up adding functionality to Slider that would be benefit from the added reusability of this function. At that point in time you can avoid rewriting the function, or worse yet creating an essentially duplicate function for the new usecase.

In situations where self is not the target, merely a reference to the parent, either example is fine. If your function already has a lengthy list of arguments it accepts, setting self inside the function instead of passing it as an argument is often a good idea. Lots of arguments make it harder to understand, refactor, and test, code.

You only need self in wasClicked , in the other cases use this :

Slider = {

    init: function() {
        foo = $('.someElement');
        this.bindEvent();
    },

    bindEvent: function() {
        this.foo.on('click', this.wasClicked);
    },

    wasClicked: function(e) {
        var self = Slider;
        e.doSomething;
        self.done();
    }

}

Slider.init();

Regarding your edit: in the first option, the event handler won't work, because you're calling it right away instead of passing a reference. You'd have to modify the method to return a function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM