Javascript 使用变量调用javascript对象方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6737840/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
call javascript object method with a variable
提问by Achshar
i am new to object oriented javascript. I have a variable whose value i would like to use to call an object's method. like this..
我是面向对象的 javascript 的新手。我有一个变量,我想用它的值来调用对象的方法。像这样..
var foo = {
bar: function() {},
barr: function() {}
}
now there is a variable whose value can be any of the two method's names bar
and barr
i want to call them with something like
现在有一个变量,它的值可以是这两个方法的名称中的任何一个bar
,barr
我想用类似的东西来调用它们
var myvar = 'bar';
foo.{myVar}();
回答by pixelfreak
So I assume you want to call the appropriate function dynamically based on a string. You can do something like this:
所以我假设您想根据字符串动态调用适当的函数。你可以这样做:
var myVar = 'bar';
foo[myVar]();
Or you can also use eval
but this is riskier (prone to injection attack) and slower (don't do this!:P):
或者您也可以使用,eval
但这风险更高(容易受到注入攻击)且速度更慢(不要这样做!:P):
var myVar = 'bar';
eval('foo.' + myVar + '()');
回答by yan
Since you can access elements of an object via subscript notation, the following will do what you're looking for:
由于您可以通过下标符号访问对象的元素,因此以下内容将满足您的需求:
var myVar = 'bar';
foo[myVar]();
回答by Justin Ethier
You can just say:
你可以说:
foo[myVar]();
Since foo
is a JavaScript object, this code will reference the member by name contained in the myVar
variable.
由于foo
是一个 JavaScript 对象,此代码将通过myVar
变量中包含的名称引用该成员。
回答by wanovak
var foo = {
bar: function() { alert('bar'); },
barr: function() { alert('barr'); }
}
var myvar = 'bar';
foo[myvar](); // alert 'bar'
回答by Mrchief
Use something like: foo[myVar]();
使用类似的东西: foo[myVar]();
回答by John Hartsock
it should be something like this
它应该是这样的
foo[myvar]();