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?
Summarizing your question, you ask why in your first snippet,
this.xisundefined:It doesn’t make sense at all, the
thisvalue should refer to the global object -if your code were on strict mode, you would get aTypeError, sincethisby itself would beundefined-.The only way I think where
this.xcould beundefined, is in the case that the variable declaration ofxwas made within a function.Check the two following examples: 1 and 2, it’s exactly the same code, the difference is that the second one, the code is wrapped in an
onloadevent handler, so thexvariable doesn’t exist in the global scope (window.xisundefined)…