2

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'
Aadit M Shah
  • 67,342
  • 26
  • 146
  • 271
blue ghhgdtt
  • 847
  • 2
  • 10
  • 16

1 Answers1

6

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):

T.J. Crowder
  • 879,024
  • 165
  • 1,615
  • 1,639