Javascript 'this' keyword Inside a Nested Function
-
15-06-2021 - |
Domanda
This Javascript code is using the 'this' keyword inside a nested function (which is nested within a constructor):
o=new MyCtor();
for (var p in o) {
print(p);
print(o[p]);
}
function MyCtor() {
this.a=1;
var instance=this;
nested();
function nested() {
this.b=2;
instance.c=3;
}
}
Result is this:
a
1
c
3
Note the print() just dumps the output to the screen like alert() in a browser (I'm testing with a standalone Spidermonkey, not inside a browser). Notice that property 'b' cannot be created by the 'this.b'.
Just wondering what is 'this' refering to in a nested function inside a constructor?
Soluzione
Since you are calling the function directly (not as an object property) and without the new
keyword, this
is the default object (window
in a web browser, global
in node, etc).
See a live demo on jsfiddle.
Altri suggerimenti
It refers to the Window. See for yourself by running this fiddle and opening the console: http://jsfiddle.net/sveinatle/9brLj/