Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing global property using "this" keyword inside a function

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?

like image 890
Benny Tjia Avatar asked Apr 23 '26 19:04

Benny Tjia


2 Answers

You've got the wrong end of the stick. The value of this depends on how the function is called, not how it is defined.

  • If you call window.foo() then (inside foo) this will be window
  • If you call bar.foo() then this will be bar (although you need to copy foo so it is a property of bar first)
  • If you call baz.bar.foo() then this will be bar (you only ever get the parent object via this)
  • If you call foo.call(bar) then this will also be bar as call lets you override this
  • If you call new foo() then this will be the new object being created

The default object is window, so if you just call foo() then that is the same as window.foo().

It doesn't matter what scope the function is defined in.

like image 91
Quentin Avatar answered Apr 25 '26 08:04

Quentin


Summarizing your question, you ask why in your first snippet, this.x is undefined:

var x = "Global";
function foo(){
    alert(this.x);   //undefined     
}
foo();

It doesn't make sense at all, the this value should refer to the global object -if your code were on strict mode, you would get a TypeError, since this by itself would be undefined-.

The only way I think where this.x could be undefined, is in the case that the variable declaration of x was 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 onload event handler, so the x variable doesn't exist in the global scope (window.x is undefined)...

like image 45
Christian C. Salvadó Avatar answered Apr 25 '26 08:04

Christian C. Salvadó



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!