相关疑难解决方法(0)

嵌套函数中的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();
Run Code Online (Sandbox Code Playgroud)

javascript nested function this

82
推荐指数
5
解决办法
4万
查看次数

标签 统计

function ×1

javascript ×1

nested ×1

this ×1