开发者

Why doesn't this use of javascript functions in an array work?

开发者 https://www.devze.com 2023-01-31 14:41 出处:网络
I am trying to create an array of functions so I can call one depending on an index. The set function doesn\'t work.The setF1 and setF2 functions do.

I am trying to create an array of functions so I can call one depending on an index. The set function doesn't work. The setF1 and setF2 functions do. What is the design decision that made things work this way?

You can find the test page at jrootham.tjddev.net/test/test.html

I can't seem to paste the test code here.

<!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){t开发者_开发知识库his.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>


The reason why this doesn't work is because this in the context of call:this.f1 is actually referencing window and not thing.

this is only referencing thing from within thing's member functions.

The following would work however:

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];
0

精彩评论

暂无评论...
验证码 换一张
取 消