【问题标题】:Why doesn't this use of javascript functions in an array work?为什么在数组中使用 javascript 函数不起作用?
【发布时间】:2010-12-17 05:57:24
【问题描述】:

我正在尝试创建一个函数数组,以便可以根据索引调用一个函数。 设置功能不起作用。 setF1 和 setF2 函数可以。 使事情以这种方式工作的设计决策是什么?

您可以在 jrootham.tjddev.net/test/test.html 找到测试页面

我似乎无法在此处粘贴测试代码。

<!DOCTYPE HTML>
<html>     
  <head>    
  <script type="text/javascript">
  var thing =
  {
    f1 : function() {alert(1);},
    f2 : function() {alert(2);},
    setF1 : function() {this.call = this.f1;},
    setF2 : function() {this.call = this.f2;},
    list : [this.f1, this.f2],
    set: function(index){this.call=this.list[index];},
    call : this.f1
  }
  </script>     
  </head>     
  <body>
    <button type="button" onClick="thing.set(0)">Set 0</button>     
    <button type="button" onClick="thing.set(1)">Set 1</button>     
    <button type="button" onClick="thing.setF1()">Set F1</button>     
    <button type="button" onClick="thing.setF2()">Set F2</button>     
    <button type="button" onClick="thing.call()">Call</button>     
  </body>
</html>

【问题讨论】:

  • {} 创建一个object[] 创建一个 array。两者之间存在显着差异。

标签: javascript arrays function


【解决方案1】:

这不起作用的原因是thiscall:this.f1 的上下文中实际上是在引用window不是 thing

this 仅在 within thing 的成员函数中引用 thing

以下可以工作:

var thing = { //watch out for semicolon insertion...
  f1 : function() {alert(1);},
  f2 : function() {alert(2);},
  setF1 : function() {this.call = this.f1;},
  setF2 : function() {this.call = this.f2;},
  set: function(index){ this.call=this.list[index]; },
  call : function() {
     this.f1();
  }
};
thing.list = [thing.f1, thing.f2];

【讨论】:

  • 内部:[this.f1, this.f2] 不起作用,因为 this==window; [thing.f1, thing.f2] 不起作用,因为尚未定义事物。
猜你喜欢
  • 1970-01-01
  • 2018-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
相关资源
最近更新 更多