Reputation: 1637
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
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