Razer
Razer

Reputation: 39

Why this keyword is not referring to window in a stand alone JS function

I was just trying scoping and this keyword in JS, While writing the below code i really got confused as i was expecting console.log(a) after calling f() to be 5, but instead it gave me 10.

My question is :

  1. Isn't the this keyword in a standalone function refers to window ?
  2. If yes, then isn't the code inside the function is the same as window.a = 5 and the value of a should be updated to 5?
  3. If no, why console.log(this) results in window, but value of a (which is global) isn't updated ?

JS Fiddle

var a = 10;

function f(){
    this.a = 5;
    console.log(a);
}

console.log(a);
f();
console.log(a);

Upvotes: 1

Views: 109

Answers (4)

Felix Kling
Felix Kling

Reputation: 817238

If the code is run in global scope, then it will produce the result you expect. The problem with your jsFiddle is that it does not run in global scope. Hence var a; creates a local variable a, while this.a refers to the global variable a.

Here is your code run in global scope: http://jsfiddle.net/grayoork/ (note the "no wrap - ...") setting.

Reference: MDN - this.


So both var a; and this.a will refer to the same variable iff:

  • the code runs in global scope
  • this inside f refers to the global object, which is the case if
    • f is executed as f() and not bound, or it is bound to the global object
    • f is not in strict mode.

Upvotes: 9

Scimonster
Scimonster

Reputation: 33409

This is unique to JSFiddle, due to the fact that they wrap their functions. If you use Chrome's console, and click on the file it's being logged from, you get something other than your code. Here's the actual JS that's being executed:

window.onload=function(){
var a = 10;

function f(){
    this.a = 5;
    console.log(this);
}

console.log(a);
f();
console.log(a);


}

Now it's clear what's going on - a isn't global at all! It's scoped to the onload function.

Upvotes: 1

Gavin
Gavin

Reputation: 516

this refers to the current context - see the javascript call and apply functions which can switch contexts within a function this refers to the function unless the function was called in such a way as to set the context eg someobject.function() or through the use of call or apply

Upvotes: 0

Kashif Umair Liaqat
Kashif Umair Liaqat

Reputation: 1074

If this is used inside a function it's scope is only for that function. So var a = 10; and this.a = 5 are two different variables.

Upvotes: -1

Related Questions