3

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?

Bojangles
  • 99,427
  • 50
  • 170
  • 208
Dinkheller
  • 4,631
  • 5
  • 39
  • 67

4 Answers4

6

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:

MSeifert
  • 145,886
  • 38
  • 333
  • 352
aymericbeaumet
  • 6,853
  • 2
  • 37
  • 50
1

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';

  }

}
Ahmad
  • 1,913
  • 13
  • 21
  • This is great for private members and complex self building objects. However you take a significant performance hit with this on both CPU and memory. If you are making a class that is instantiated many times such as an object wrapper then you should use prototype inheritance. – jgmjgm Jun 20 '16 at 19:05
1

To answer the specific question, and not get too theoretical, there is a very very small difference in speed between your two examples.

Creating the extra variable lookup will very slightly slow down your script. Because creating the variable is one extra operation and the two pieces of code are otherwise essentially the same. Since you are creating objects with member functions, a very small performance hit could be magnified if you have thousands of objects.

As always, your performance is going to vary across browsers. Here's a jsPerf test that shows that the difference is minimal:

http://jsperf.com/variable-caching-this

Look at Ops/Sec

Chrome 36.0.1985.143 m - Excluding variable definition is faster

Opera 24.0 - Excluding variable definition is faster

Firefox 31.0 - Excluding variable definition is faster

IE 11 - Excluding variable definition is faster

Alex W
  • 37,233
  • 13
  • 109
  • 109
  • Actually this answer was what I was asking for, but aymericbeaumet had some more information. To make it easier for other users to find a detailed answer I have chosen to mark his answer as 'best answer'. Still personally I found your information exactly what I was looking for, due to the added link. Thanks a lot. – Dinkheller Aug 27 '14 at 13:03
  • If this answer is more relevant to your question, accept it ;) Mine will be displayed below accordingly to its number of votes. – aymericbeaumet Aug 27 '14 at 13:04
  • @Alex W: though I agree with your point, there something on which I struggle. Do you have any source confirming: `JavaScript is already storing this in the object's prototype`? AFAIK it is stored in the execution context (not accessible from the user). – aymericbeaumet Aug 27 '14 at 13:08
  • @AlexW: I meant the execution context is not directly accessible to the user. `it is still stored in memory and therefore no benefit is provided by caching access to it in a variable`: I'm not agreeing here, global variables are also in memory and there is a benefit to cache them. – aymericbeaumet Aug 27 '14 at 14:32
0

Is there a difference if I call upon the scope several times?

For me there is no difference when you call just the scope several times compared to variable because it does the same job only you assigned this to a variable.

Do I use a variable or just use the scope? It depends upon the situation, because sometimes you need to cached the this so that it will not mixed up to other. Consider this.

function blabla() {
   var thisis = this;
   $.each(function() { 
     //`this` here is not equal to `thisis` so if you need `thisis` here you will assign to a variable first.
   });
}

Im sorry for using jquery here.

HTTP
  • 1,674
  • 3
  • 17
  • 22