开发者

Execute JavaScript function from object

开发者 https://www.devze.com 2022-12-21 12:55 出处:网络
Is it possible to execute function this way: this.values(value); not this.values[value](); this.values[value].call();

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 */ }
  开发者_JAVA技巧};

  return this.values[value]();

}

write("red");


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.


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


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

精彩评论

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

关注公众号