1

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");
1
  • 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. Commented Feb 23, 2010 at 15:50

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Best to put the keys (red, orange, blue) in quotes in case you accidentally use a keyword.
@Phil H, you're right, It's a bad habit, I find it easier to read.
1

No. But there isn't anything wrong with how its done at the moment.

Comments

0

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");

Comments

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.