Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript this refers to window instead of object inside function

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.

like image 778
Makzan Avatar asked Apr 05 '13 10:04

Makzan


1 Answers

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

like image 96
Quentin Avatar answered Oct 04 '22 15:10

Quentin