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:
They're both the same except that me is a reference to this.
That can be very useful when you have different contexts inside your main one because this will always refer to the context its called in, while me will be reference to your main context.
Example
function MainFunction(){
var me = this;
function secondFunction(){
// this refers to this anonymous function
this.varName = 'something';
// me is a reference to MainFunction
me.varName = 'something';
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With