Should it be stored in a variable when accessing object methods? (Javascript)

Where I reference the JavaScript object several times using this

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

Is there any performance gain and should I store thisin a variable? How:

init : function() {
    var self = this;

    self.method1();
    self.method2(); 
    self.method3();  
}
+3
source share
1 answer

There is no need to store the link thisin a variable unless you need to pass this context to closure.

Here is an example of when you might need to pass the pointer thisto close, for example, the click event for an element that needs a link to what the pointer pointed to thisin the external, parent event context:

init : function() {

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

}

-, . , , .

+4

All Articles