Is it possible to execute function this way:
this.values(value);
not
this.values[value]();
this.values[value].call();
If so, how? Or any other methods? Thank you.
Here is my code:
write: function(value) {
this.values = {
"red": function() { /* do something */ },
"orange": function() { /* do something */ },
"blue": function() { /* do something */ }
};
return this.values[value]();
}
write("red");
asked Feb 23, 2010 at 15:19
Bambert
2951 gold badge3 silver badges6 bronze badges
-
I don't see a problem here, you still get to call write("red"), don't you? Might be worth moving the values map outside the function if you'll need it elsewhere.Phil H– Phil H2010年02月23日 15:50:09 +00:00Commented Feb 23, 2010 at 15:50
3 Answers 3
May be you could use a var inside:
write: function(value) {
var values = {
red: function() { /* do something */ },
orange: function() { /* do something */ },
blue: function() { /* do something */ }
};
return values[value];
}
And return the function instead of running it inside. And call it after.
answered Feb 23, 2010 at 15:30
Mic
25.2k9 gold badges62 silver badges71 bronze badges
No. But there isn't anything wrong with how its done at the moment.
answered Feb 23, 2010 at 15:49
Matt
75.5k26 gold badges156 silver badges181 bronze badges
Comments
You could always do this:
write: function(value) {
switch(value){
case "red":
/* do something */
break;
case "orange":
/* do something */
break;
case "blue":
/* do something */
break;
default:
/* do something */
break;
}
}
write("red");
answered Apr 10, 2013 at 20:45
Finickyflame
86310 silver badges12 bronze badges
Comments
lang-js