Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'this' keyword in javascript returns differently [duplicate]

Tags:

javascript

Why does the this keyword express different values in the following code?

var t = {
    a: "a",
    b: {
        c: "c",
        d: function () {
            return this;
        }
    },
    f: function () {
        return this;
    },
    g: this
}

var k = t.f(),
    l = t.g;

alert(k); // returns [object object] i.e 't'
alert(l); // returns [object DOMWindow] i.e 'window'
like image 876
blue ghhgdtt Avatar asked Jun 17 '26 03:06

blue ghhgdtt


1 Answers

If you're used to some other programming languages like C++, Java, or C#, the first thing about understanding this in JavaScript is: It's completely different from this in those other languages, even though it looks very similar and sometimes even acts similarly.

When you're creating the t object, you capture the value of this as of when the object is created and store it in the property g. So g will be whatever this was when t was created. Because this refers to the global object (window, on browsers) by default unless you're using strict mode, that's what t.g will be.

In contrast, your t.f function is getting called and is returning the value of this that exists within the call. In JavaScript (for now), this is determined entirely by how a function is called rather than where it's defined. In particular, when you call a function as part of an expression that retrieved the function from a property reference, this is set to the object within the call. This is a complex way of saying when you do t.f(), during the call to f, this will be t.

Some further reading (on my blog):

  • Mythical methods
  • You must remember this
like image 58
T.J. Crowder Avatar answered Jun 18 '26 15:06

T.J. Crowder



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!