Javascript 如何使用参数值调用函数?
是否有任何方法可以使用传递的参数在javascript中调用函数 例如:Javascript 如何使用参数值调用函数?,javascript,Javascript,是否有任何方法可以使用传递的参数在javascript中调用函数 例如: 谢谢 Javascript对象属性的行为与此类似this.a==this['a'] var Animal = (function(){ function Animal(type){ this[type](); //eg this.snake(); if the parameter type is "snake" } return Animal;
谢谢 Javascript对象属性的行为与此类似
this.a==this['a']
var Animal = (function(){
function Animal(type){
this[type](); //eg this.snake(); if the parameter type is "snake"
}
return Animal;
})();
您可以像引用数组一样引用它。在您的情况下,它将是
此[类型]
function Animal(type){
this[type]();
}
此外,如果您不知道对象或变量是全局变量,那么您可以在相同的上下文中使用window
like。比如说
var apple = 'tasty';
var fruit = 'apple';
console.log(window[fruit]); // Will give `tasty` as output
它们不像数组。@Starx是对的,函数不是数组,它们是对象!对象有点表示法和括号表示法。我说它们的行为类似于关联数组,显然对象不是数组,行为类似于关联数组也是数组。
var apple = 'tasty';
var fruit = 'apple';
console.log(window[fruit]); // Will give `tasty` as output