0

我正在创建一个这样的原型类,但我想使用字符串作为函数名来调用函数。我找到了窗口名称;例如某处,但它不适用于我的情况。

function someObj() {

  this.someMethod = function() {
    alert('boo'); 
    name = "someOtherMethod";
    window[name]();
  }

  var someOtherMethod = function() {
    alert('indirect reference');
  }

}
4

4 回答 4

1

这是因为它不是函数内部定义的对象"someOtherMethod"的成员。windowsomeObj

于 2012-09-29T18:49:06.823 回答
0

window仅适用于全局变量。

除非您使用 ,否则您不能通过字符串访问局部变量eval,这几乎总是一个坏主意。

另一种方法是使用对象。这允许您使用字符串查找属性。

function someObj() {

  var methods = {};

  methods.someMethod = function() {
    alert('boo'); 
    var name = "someOtherMethod";
    methods[name]();
  }

  methods.someOtherMethod = function() {
    alert('indirect reference');
  }

}
于 2012-09-29T18:49:02.473 回答
0

someOtherMethod 从窗口中隐藏,仅存在于原型的范围内。

尝试将其移出。

function someObj() {
    this.someMethod = function() {
       alert('boo'); 
       name = "someOtherMethod";
       window[name]();
     }
}

var someOtherMethod = function() {
    alert('indirect reference');
}

尽管使用全局变量是个坏主意。

于 2012-09-29T18:49:42.230 回答
0

创建您自己的方法哈希:

function someObj() {

  this.someMethod = function() {
    alert('boo'); 
    name = "someOtherMethod";
    methods[name]();
  }

  var methods = {
    someOtherMethod : function() {
        alert('indirect reference');
    }
  };
}

您的变量是函数的本地变量,因此它不会位于window. 即使您在全局范围内工作,使用自己的对象也比依赖 window 更好,这样可以避免名称冲突。

于 2012-09-29T18:52:06.777 回答