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
thisreference 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
thispointer into a closure, such as a click event on an element that needs a reference to whatever thethispointer was pointing to in the outer, parent context of the event: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.