[英]How can I execute a function using a variable name?
Here is my code: 这是我的代码:
$(function(){ function myfunc(){ alert("executed"); } var function_name = "myfunc"; window[function_name](); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
As you can see, that function is not defined. 如您所见,该函数未定义。 Why?
为什么? And how can I make it working?
我该如何运作呢?
The function is not defined in the global scope so it's not a member of the window object. 该函数未在全局范围内定义,因此它不是window对象的成员。
You can attach the function to the window object like this. 您可以像这样将函数附加到窗口对象。
$(function(){
window.myfunc = function(){
alert("executed");
};
var function_name = "myfunc";
window[function_name]();
})
It works only for global functions, because the scope is identically with the window
object. 它仅适用于全局函数,因为作用域与
window
对象相同。
You could assing a function to a wanted property of the window
object, just as to any other object. 您可以将函数与其他任何对象一样,分配给
window
对象的所需属性。
function myfunc(){ alert("executed"); } $(function(){ var function_name = "myfunc"; window[function_name](); window.foo = _ => console.log('foo'); window.foo(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
While the direct answer to your question is that your function wasn't defined as a Global and so, attempting to call it as a property of window
fails, putting your function into Global scope is not really a good answer. 虽然直接回答您的问题是您的函数未定义为Global,所以尝试将其作为
window
的属性来调用失败,但是将函数置于Global范围并不是一个好的答案。
Instead, make the function a method of a user-defined object (that can be put into any scope you like) and call the function as a property of that object: 而是将函数作为用户定义对象的方法(可以放入您喜欢的任何范围),然后将该函数作为该对象的属性进行调用:
// Immediately-Invoked Function Expression (IIFE) // that keeps all of its contents out of the Global scope (function(){ let functionHolder = { someFunction : function(){ console.log("You did it!"); } }; // Set up a variable that has the same name as the function let funcName = "someFunction"; // Call the function via the object functionHolder[funcName](); })()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.