user409841
user409841

Reputation: 1637

Javascript calling function reference

function (type, a, b) {
  var types = {
    'add' : this.add(a,b),
    'subtract' : this.subtract(a,b),
    'multiply' : this.multiply(a,b)
  };

  if(types[type])
    return types[type];
}

This might be simple, but I can't seem to figure it out. I want a map of strings to function references (with parameters pre populated), and if the type is valid, I want to call the specified function in the map.

this setup works, but it's actually calling the methods when it's initializing the array which isn't what i want. i only want to call the function if the type is valid. I just want to keep a reference to the function call I want to make when I set up the function. Is this possible? Thanks.

Upvotes: 1

Views: 80

Answers (1)

Felix Kling
Felix Kling

Reputation: 816252

It looks like you want:

function (type, a, b) {
  var types = {
    'add' : this.add, // assign reference
    'subtract' : this.subtract,
    'multiply' : this.multiply
  };

  if(types[type])
    return types[type](a, b); // call function
}

But you could also avoid creating the object entirely:

function (type, a, b) {
  if(['add', 'subtract', 'multiply'].indexOf(type) > -1)
    return this[type](a, b);
}

Upvotes: 4

Related Questions