简体   繁体   中英

Should this be stored in a variable when referencing to an objects methods? (JavaScript)

Where I reference to a JavaScript object multiple times using this

var myObj = {
   method1 : function() {},
   method2 : function() {},
   method3 : function {},
   init : function() {
       this.method1();
       this.method2(); 
       this.method3();  
   }
};

Is there any kind of performance gain and should I store this in a variable? Like:

init : function() {
    var self = this;

    self.method1();
    self.method2(); 
    self.method3();  
}

There is no need to store the this reference in a variable, unless you need to pass that context into a closure.

Here is an example of when you may need to pass the this pointer into a closure, such as a click event on an element that needs a reference to whatever the this pointer was pointing to in the outer, parent context of the event:

init : function() {

    $('.someElem').click( 
        (function(self) {
            return function() {
                self.method1();
                self.method2(); 
                self.method3();  
            }
        })(this)   // pass "this" into the "self" parameter as an argument
    );

}

In your case, you're needlessly creating a local variable and assigning it something when you really don't need to. It's redundant, and also creates a variable that isn't needed.

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