JavaScript this refers to window instead of object inside function

不羁岁月 提交于 2019-11-26 23:16:17

问题


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.


回答1:


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




回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/15831509/javascript-this-refers-to-window-instead-of-object-inside-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!