嵌套函数中的Javascript“this”指针我有一个关于如何在嵌套函数场景中处理“this”指针的问题。假设我将以下示例代码插入到网页中。当我调用嵌套函数“doSomeEffects()”时出错。我检查了Firebug,它表明当我在嵌套函数中时,“this”指针实际上指向全局“窗口”对象 - 我没想到。我一定不能理解正确的东西,因为我认为既然我在对象的函数中声明了嵌套函数,它应该具有与函数相关的“局部”范围(即“this”指针将指向对象本身就像它是如何在我的第一个“如果”声明中。任何指针(没有双关语意)将不胜感激。var std_obj = {
options : { rows: 0, cols: 0 },
activeEffect : "none",
displayMe : function() {
// the 'this' pointer is referring to the std_obj
if (this.activeEffect=="fade") { }
var doSomeEffects = function() {
// the 'this' pointer is referring to the window obj, why?
if (this.activeEffect=="fade") { }
}
doSomeEffects();
}};std_obj.displayMe();
3 回答

萧十郎
TA贡献1815条经验 获得超13个赞
this
不是闭包范围的一部分,它可以被认为是在调用站点绑定的函数的附加参数。如果该方法未作为方法调用,则将全局对象作为传递this
。在浏览器中,全局对象与之相同window
。例如,考虑以下功能,
function someFunction() {}
和以下对象,
var obj = { someFunction: someFunction };
如果使用方法语法调用函数,例如,
obj.someFunciton();
然后this
必然会obj
。
如果你直接调用someFunction(),比如
someFunction();
然后this
绑定到全局对象,即window
。
最常见的工作是将其捕获到闭包中,例如:
displayMe : function() { // the 'this' pointer is referring to the std_obj if (this.activeEffect=="fade") { } var that = this; var doSomeEffects = function() { // the 'this' pointer is referring to global // that, however, refers to the outscope this if (that.activeEffect=="fade") { } } doSomeEffects(); }

饮歌长啸
TA贡献1951条经验 获得超3个赞
由于这似乎是同类中最受欢迎的问题之一,所以这些年来,让我使用箭头函数添加ES6解决方案:
var std_obj = { ... displayMe() { ... var doSomeEffects = () => { ^^^^^^^ ARROW FUNCTION // In an arrow function, the 'this' pointer is interpreted lexically, // so it will refer to the object as desired. if (this.activeEffect=="fade") { } }; ... }};
添加回答
举报
0/150
提交
取消