我有一个JavaScript函数的名称作为字符串。如何将其转换为函数指针以便稍后调用?
根据具体情况,我可能还需要将各种参数传递到方法中。
一些函数可以采用namespace.namespace.function(args[…])的形式。
我有一个JavaScript函数的名称作为字符串。如何将其转换为函数指针以便稍后调用?
根据具体情况,我可能还需要将各种参数传递到方法中。
一些函数可以采用namespace.namespace.function(args[…])的形式。
当前回答
我认为一种优雅的方法是在哈希对象中定义函数。然后,您可以使用字符串从哈希中引用这些函数。如。
var customObject = {
customFunction: function(param){...}
};
然后你可以调用:
customObject['customFunction'](param);
其中customFunction将是一个匹配对象中定义的函数的字符串。
更新
这个答案似乎对许多程序员有帮助,所以这里有一个更新版本。
在ES6中,你还可以使用计算属性名,这将允许你避免魔法字符串。
const FunctionNames = Object.freeze({ FirstFunction:“FirstFunction”, SecondFunction:“SecondFunction” }); … var customObject = { [functionname。FirstFunction]:函数(参数){…} [functionname。SecondFunction]:函数(参数){…} }; … customObject [FunctionNames.FirstFunction](参数);
其他回答
小心! !
在JavaScript中应该尽量避免通过字符串调用函数,原因有两个:
原因1:一些代码混淆器会破坏你的代码,因为它们会改变函数名,使字符串无效。
原因2:维护使用这种方法的代码要困难得多,因为定位字符串调用的方法的用法要困难得多。
我认为你不需要复杂的中间函数或eval,也不需要依赖像window这样的全局变量:
function fun1(arg) {
console.log(arg);
}
function fun2(arg) {
console.log(arg);
}
const operations = {
fun1,
fun2
};
operations["fun1"]("Hello World");
operations.fun2("Hello World");
// You can use intermediate variables, if you like
let temp = "fun1";
operations[temp]("Hello World");
它也可以使用导入的函数:
// mode.js
export function fun1(arg) {
console.log(arg);
}
export function fun2(arg) {
console.log(arg);
}
// index.js
import { fun1, fun2 } from "./mod";
const operations = {
fun1,
fun2
};
operations["fun1"]("Hello World");
operations["fun2"]("Hello World");
因为它使用的是属性访问,所以它将在最小化或混淆中存活下来,这与您在这里找到的一些答案相反。
你只需要通过window[<方法名>]将字符串转换为指针。 例子:
var function_name = "string";
function_name = window[function_name];
现在你可以把它当做一个指针。
也有一些非常有用的方法。
http://devlicio.us/blogs/sergio_pereira/archive/2009/02/09/javascript-5-ways-to-call-a-function.aspx
var arrayMaker = {
someProperty: 'some value here',
make: function (arg1, arg2) {
return [ this, arg1, arg2 ];
},
execute: function_name
};
不使用eval('function()'),您可以使用new function(strName)创建一个新函数。下面的代码是使用FF, Chrome, IE测试的。
<html>
<body>
<button onclick="test()">Try it</button>
</body>
</html>
<script type="text/javascript">
function test() {
try {
var fnName = "myFunction()";
var fn = new Function(fnName);
fn();
} catch (err) {
console.log("error:"+err.message);
}
}
function myFunction() {
console.log('Executing myFunction()');
}
</script>