3

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!

0

2 Answers 2

2

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;
    })();
Sign up to request clarification or add additional context in comments.

4 Comments

They do not act like arrays.
@Starx is right, functions are not arrays, they're objects! And objects have dot notation and bracket notation.
i said they act like associative arrays , obviously objects are not arrays,, act like
Associative array are also arrays.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.