I have this piece of code
var f = function() {
this.x = 100;
(
function() {
x = 20;
}
)();
};
var a = new f;
console.log(a.x);
I am wondering why a new variable x is created at global scope, and the output is 100, not 20.
If I write instead
var x = 100;
the nested function changes the same x’s value.
It seems that creating x via
this.x = 100
places x outside the scope of function f. If that is the case, where is it defined? And how can it be accessed?
EDIT : Fixed a typo : console.log(a.x) instead of console.log(x)
The statement:
Does not create a variable in the current scope, it sets a property
xon whatever objectthisrefers to. In your casethiswill be the object just instantiated vianew f, the same object that will be returned byfand assigned toa.When you say:
JavaScript looks for an
xin the current scope and doesn’t find it, so it looks in the next scope up, etc., until it gets to the global scope. If it doesn’t findxin any accessible scope it creates a new global variable as you have seen.To access the property
xfrom within a nested function the usual practice is to store a reference tothisin a local variable and then the nested function can reference that variable:The other way to do it is to reference
this.xin the inner function, provided you call the inner function via the.call()method so that you can explictly setthisto be the same as in the (outer)ffunction:Further reading:
thisoperator