简体   繁体   English

如何从字符串的方法名称中调用JavaScript函数?

[英]How do call a javascript function from its method name in string?

Does anybody know how to call a javascript function such as 有人知道如何调用javascript函数吗?

function sampleCallback() {
      alert("hello");
}

from a string "sampleCallback()"? 从字符串“ sampleCallback()”?

I have a multidimensional array like so: 我有一个这样的多维数组:

hintSlidesArray = [
                    [{ "element": "noelement" }, { "hintMessage": "Welcome"}, "callback": "sampleCallback" }],
                  ];

And would like to pass the callback string to it so that I can run it from where im reading the array. 并希望将回调字符串传递给它,以便我可以从读取数组的位置运行它。

Any global variables - including functions - are properties of the global object. 任何全局变量(包括函数)都是全局对象的属性。 In a browser environment this is window . 在浏览器环境中,这是window So you can use the array subscript syntax to access the property you are looking for: 因此,您可以使用数组下标语法访问所需的属性:

window[hintSlidesArray[0][2].callback]();

If you need to specify a value for this , you can use .call() or .apply() : 如果你需要指定的值this ,你可以使用.call().apply()

window[hintSlidesArray[0][2].callback].call(value_for_this);

However, you should really consider storing the function instead of its name in your object. 但是,您应该真正考虑将函数而不是函数名称存储在对象中。 If the function is already defined in the current scope (or the global scope) when creating the object, this is as easy as removing the quotes from the function name. 如果在创建对象时已经在当前作用域(或全局作用域)中定义了函数,则就像从函数名称中删除引号一样容易。

You can use call or apply method. 您可以使用callapply方法。 For example: 例如:

hintSlidesArray[0][2].callback.call(this)

您可以使用window对象调用javascript函数:

var functionResult = window[myFunctionName];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM