"this"函数的作用域无效



我有以下功能:

  function a() {
    var d = {
      foo : "text"
    };
    for(var b in c) {
      if(c.hasOwnProperty(b)) {
        d[b] = function() {
          return c[b].apply(this, arguments);
        };
      }
    }
    return d;
  }
  var c = {
    a : function() { alert(this.foo); },
    b : function() { return this.a(); }
  }
  a().a(); // nothing happens
  // but the following works :
  var c = {
    a : function() { alert(this.foo); }
  }
  a().a(); // output : text

我认为发生这种情况是因为.apply方法中的this。我该怎么解决这个问题?

它不起作用,因为函数"a"中的迭代器变量"b"被每个闭包共享。

试试这个:

for(var b in c) {
  if(c.hasOwnProperty(b)) {
    d[b] = function(b) {
      return function() { return c[b].apply(this, arguments); };
    }(b);
  }
}

这是作为jsfiddle的工作版本。

a()在全局范围内执行。当您调用c[b].apply(this,arguments)时,它也在全局范围内执行。for循环前后迭代,它首先遇到b,它在全局范围内执行b,全局范围内调用a,在c上循环,全局范围外调用b。。。

结果:RangeError:超过的最大调用堆栈大小

最新更新