I do know that in javascript, when you use "this"
keyword inside a function, then "this"
would refer to the 'owner' of that function according to Quirksmode website. Therefore when we have a function and we use "this"
inside it, then "this"
refers to the global (window) object.
I am a little confused on how "this"
works, for example in the code below, "this"
then should be able to resolve x
since x
is pretty much a property of global object (in this case window). But this.x
in this case alerts "undefined"
instead of the x
value.
var x = "Global";
function foo(){
alert(this.x); //undefined
};
foo();
I then tried some other things too:
function bar(){
function foo(){
alert(this); //[Object DOMWindow]
};
foo();
};
bar();
If my understanding is correct, then 'this'
should refer to bar()
in that second case since it is the owner of foo()
, but why is that it instead still refers to the global object?
Can someone explain what is the correct theory regarding "this" keyword?