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>
Brad Mace
28k19 gold badges110 silver badges152 bronze badges
1 Answer 1
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];
answered Dec 17, 2010 at 6:00
Jacob Relkin
164k34 gold badges352 silver badges321 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Jim Rootham
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.
lang-js
{}creates anobject;[]creates anarray. There is a significant difference between the two.