1
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.

4
  • 1
    Where is this.add defined? What is this supposed to be here? Commented Feb 2, 2014 at 0:21
  • The expression this.add(a,b) is evaluated during the object construction. You probably want to use a closure (if using a/b), for whatever operation contract you have in mind. Commented Feb 2, 2014 at 0:21
  • 2
    If you want only the function reference, then remove the brackets and parameters. Commented Feb 2, 2014 at 0:21
  • make no sense to re-initialize types hash each time when code enters function Commented Feb 2, 2014 at 0:22

1 Answer 1

4

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);
}
Sign up to request clarification or add additional context in comments.

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.