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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:59:17  来源:igfitidea点击:

call javascript object method with a variable

javascriptobject

提问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 barand barri want to call them with something like

现在有一个变量,它的值可以是这两个方法的名称中的任何一个barbarr我想用类似的东西来调用它们

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 evalbut 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 foois a JavaScript object, this code will reference the member by name contained in the myVarvariable.

由于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]();