July 20, 2013
how using parameter value to call function?
Kishor’s Question:
is there anyway 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!
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;
})();
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