Is it a bad practice to use a local variable as reference to an object property instead of the property itself?
function Apple(){
this.type = 'green appale';
}
Apple.prototype.slice = function(){
//Does this create a noticeable overhead?
var type = this.type;
//slicing action
}
The answer is both yes and no. From a performance stand point don't worry about it. This is a cake walk compared to other performance issues. Besides the rule of thumb is to write code for readability and only optimize when you need to through profiling after the fact. Don't pre optimize.
As for the caveats… If the value you are saving as an immutable value (string, int, boolean) then your are 100% safe do do this. If it is an object or array then your need to know that it is a reference and changes will affect the original variable as well. And finally if it is a function then you have to be aware that you will loose it's context in the code example above.
function foo() {}
var bar = foo; // Context is irrelevant.
function foo() {
this.baz = 'foobar';
}
var bar = foo; // You must provide a context or `this` becomes `window`.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments