Reputation: 6423
Is there any way to use passed parameter to call function in javascript.
eg:
var Animal = (function(){
function Animal(type){
this.type(); eg this.snake(); if the parameter type is "snake"
}
return Animal;
})();
var animal = new Animal("snake");
Thanks!
Upvotes: 3
Views: 74
Reputation: 9146
Javascript object properties act like associative arrays so this.a == this['a']
var Animal = (function(){
function Animal(type){
this[type](); //eg this.snake(); if the parameter type is "snake"
}
return Animal;
})();
Upvotes: 2
Reputation: 78961
You can reference it like an array. In your case it would be this[type]
function Animal(type){
this[type]();
}
Additionally, if you do not know the object or if the variable is global, then you can use window
like in the same context. For example
var apple = 'tasty';
var fruit = 'apple';
console.log(window[fruit]); // Will give `tasty` as output
Upvotes: 1