is there a difference between the following two code examples (speedwise, best practice, etc)?
This:
function() {
var me = this;
me.doSomething();
me.doAnotherThing();
};
Or this:
function() {
this.doSomething();
this.doAnotherThing();
}
Is there a difference if I call upon the scope several times? Do I use a variable or just use the scope?
In JavaScript, scopes are inherited. Therefore when you want to access a variable from a parent scope, the engine will first look in the current scope, see if it exists there, and will then search in the parent scope. It will continue until it founds what you are asking for.
The this
variable is available in the local scope (actually in the activation object) and the engine will be able to resolve it immediately. As such, there is no performance reason to cache it.
However, this becomes interesting when you access variables from parent scopes. For example let's say you want to access the document
variable (from the global scope) several times in a function. By caching it, the engine will only have to resolve it once, thus increasing the performance:
function foo() {
var doc = document;
doc.getElementsByTagName('body');
doc.querySelectorAll('div');
}
Anyway, as of today this is more interesting as a theoretical approach since most of the modern JS engines are able to optimize it nicely (http://jsperf.com/scope-resolution-cached-not-cached).
Scoping inheritance is an important part of the JavaScript language, I strongly recommend those two readings for a better comprehension: