JavaScript这是指窗口而不是函数内部的对象 [英] JavaScript this refers to window instead of object inside function
问题描述
我对JavaScript this
参考情况感到困惑.
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.
我发现greeting
函数中的this
引用了 window 范围,而不是 person 范围.
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();
(jsfiddle中的相同代码: http://jsfiddle.net/makzan/z5Zmm/)
(same code in jsfiddle: http://jsfiddle.net/makzan/z5Zmm/)
这是浏览器中的日志结果:
And this is the log result in browser:
> Object
> Window
Aloha undefined
在JS中,我知道这个引用很棘手.而且我可以通过使用.call
方法来更改范围,以使此代码起作用.
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);
但是,我很想知道为什么默认情况下this
引用 greeting 方法内的 window 范围?
However, I am curious to know why by default the this
refer to window scope inside the greeting method?
在此先感谢您的帮助.
推荐答案
this
与 scope 无关.它由 context 决定.
greeting()
在没有上下文的情况下调用该函数,因此this
是默认对象(浏览器中的window
).
greeting()
calls the function with no context, so this
is the default object (window
in a browser).
这篇关于JavaScript这是指窗口而不是函数内部的对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!