Reputation: 39
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 :
this
keyword in a standalone function refers to window
?window.a = 5
and the value of a
should be updated to 5
?console.log(this)
results in window, but value of a
(which
is global) isn't updated ?var a = 10;
function f(){
this.a = 5;
console.log(a);
}
console.log(a);
f();
console.log(a);
Upvotes: 1
Views: 109
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:
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 objectf
is not in strict mode.Upvotes: 9
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
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
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