0
a1=10;
d1=new Date();
for( var i=0;i<=100000;i++){
 a1;
}
console.log(new Date()-d1,a1===window.a1);

d2=new Date();
for( var i=0;i<=100000;i++){
 this.a1;
}
console.log(new Date()-d2,this.a1===window.a1);

d3=new Date();
for( var i=0;i<=100000;i++){
 window.a1;
}
console.log(new Date()-d3,this.a1===window.a1);

//output
116,true

53,true

98,true

In the global,a1===this.a===window.a,why the speed is so different?

(In chrome 39.0.2171.71 m)

Artjom B.
  • 58,311
  • 24
  • 111
  • 196
thinkmoe
  • 11
  • 2
  • The answer would depend on the value of `this`. – Justin Niessner Nov 30 '15 at 03:24
  • I guess, It is up to browser implementation. Chrome makes different computations on different operations, and they take different time. – Yeldar Kurmangaliyev Nov 30 '15 at 03:33
  • I try the same code in chrome newest version (47.0.2526.73 beta-m), and it output 354 true 272 true 369 true It seems that this.a1 is faster than window.a1,But I don't konw why – thinkmoe Nov 30 '15 at 06:31
  • Possible duplicate of [How does the "this" keyword work?](http://stackoverflow.com/questions/3127429/how-does-the-this-keyword-work) – Artjom B. Feb 21 '16 at 11:49

1 Answers1

0

If you use strict mode like in "use strict"; then a will need to be defined using the keyword var or as a function parameter function(a){}. window.a will always be a property in the global object window and this will be the "current execution" scope that is going to be determined by wether you are inside of a constructed object i.e (new FN()) or when binding a function to a specific object

var obj = {a:'hi'};
function greet(){console.log(this.a)};
obj.greet.bind(obj)(); //prints 'hi'

failing to comply with these rules while on strict mode will cause a compiler error.

now if you are not on strict mode not defined variable a === window.a as the system will look for a local declaration and if none is found it will assume is because is meant to be part of the global object(window when in a browser). And when in a non explicitly declared execution scope this will refer to the global object too so in some cases on plane scripts when not in strict mode a === window.a === this.a. Is because of these "confusing" behavior that the use of "strict mode" is advised. I hope this helps

Dayan Moreno Leon
  • 4,839
  • 2
  • 19
  • 24
  • Yes, it is in non-strict model, I konw the variable 'a1' is refer to thr global object. But I wonder why the window.a1 spends nearly twice time than this.a. Many thanks – thinkmoe Nov 30 '15 at 06:17
  • well, using this is always going to be faster because no lookup is needed – Dayan Moreno Leon Nov 30 '15 at 06:39