krozero
krozero

Reputation: 6423

how using parameter value to call function?

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

Answers (2)

Sarath
Sarath

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

Starx
Starx

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

Related Questions