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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!