JavaScript this refers to window instead of object inside function
Asked Answered
E

4

20

I get confused on a JavaScript this reference situation.

I am working on a code that I declare function inside an object method. (The reason is to tidy up code inside an object method, while keeping the functions private to the method.)

The following is an experiment to re-produce my problem.

I found that the this inside greeting function refers to the window scope instead of person scope.

var person = {
    nickname: "Makzan",
    sayHi: function() {
        console.log(this);
        var greeting = function() {
            console.log(this);
            return "Aloha " + this.nickname;
        }
        console.log(greeting());
    }
}
person.sayHi();

(same code in jsfiddle: http://jsfiddle.net/makzan/z5Zmm/)

And this is the log result in browser:

> Object
> Window
Aloha undefined 

In JS, I know that this reference is tricky. And I can change the scope by using .call method to make this code works.

var greeting = (function() {
    console.log(this);
    return "Aloha " + this.nickname;
}).call(this);

However, I am curious to know why by default the this refer to window scope inside the greeting method?

Thanks in advance for all your help.

Estimative answered 5/4, 2013 at 10:25 Comment(3)
It is because greeting is called without a context.Donia
Thanks all. I learn more on what 'context' means now.Estimative
Possible duplicate of How does the "this" keyword work?Followthrough
H
14

this has nothing to do with scope. It is determined by context.

greeting() calls the function with no context, so this is the default object (window in a browser).

Hypotenuse answered 5/4, 2013 at 10:27 Comment(0)
D
4

The this, references is not related to scope, it depends on the calling context.

As per the MDN doc,

In general, the object bound to this in the current scope is determined by how the current function was called

Donia answered 5/4, 2013 at 10:29 Comment(0)
N
2

Try person.nickname, this refers to the var greeting in your case

Nettie answered 5/4, 2013 at 10:27 Comment(0)
C
0

If we modify your code a little, we can see that this works:

var person = {
  nickname: "Makzan",
  greeting: function () {return "Aloha " + this.nickname;},
  sayHi: function () {return console.log(this.greeting());}
}

person.sayHi();

So we may conclude the reason that this doesn't:

var person = {
    nickname: "Makzan",
    sayHi: function () {var greeting = function () {return "Aloha " + this.nickname}; console.log(greeting()); }
};

person.sayHi();

is because for greeting() to have the this context of the person object, it must be explicitly declared as a direct property of the person object.

Consolata answered 19/8, 2022 at 13:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.