0

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){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>
1
  • {} creates an object; [] creates an array. There is a significant difference between the two. Commented Dec 17, 2010 at 6:06

1 Answer 1

2

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];
Sign up to request clarification or add additional context in comments.

1 Comment

Inside thing: [this.f1, this.f2] doesn't work because this==window; [thing.f1, thing.f2] doesn't work because thing is not defined yet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.