如何调用数组中存储的函数?求Google Apps Script中替代PHP call_user_func的安全实现方案
Great question—ditching eval() is a smart move because it exposes your code to security risks (like arbitrary code injection) and can hurt performance. In Google Apps Script, you don't need a direct equivalent to PHP's call_user_func because JavaScript (which GAS is based on) has safer, more straightforward ways to handle this. Let's break down the best approaches:
1. Store Function References Directly (Most Secure)
Instead of storing function names as strings in your array, store the actual function references. This lets you call them directly without any string parsing or risky evaluation:
const func1 = function (i) { return i }; const func2 = function (i) { return i * 2 }; const func3 = function (i) { return i * 3 }; const func4 = function (i) { return i * 4 }; // Store function references, not strings const funcs = [func1, func2, func3, func4]; function myFunction() { const item = 3; const i = 2; // Call the function directly from the array const result = funcs[item](i); console.log(result); // Output: 8 }
This is the cleanest and safest method—no security risks, and it's easier to read and maintain.
2. Use an Object to Map Function Names to Functions
If you absolutely need to work with function names as strings (e.g., if the names come from external input or config), wrap your functions in an object. This lets you look up functions by name without using eval():
const functionMap = { func1: function (i) { return i }, func2: function (i) { return i * 2 }, func3: function (i) { return i * 3 }, func4: function (i) { return i * 4 } }; const funcs = ['func1', 'func2', 'func3', 'func4']; function myFunction() { const item = 3; const i = 2; // Look up the function in the object and call it const selectedFunc = functionMap[funcs[item]]; if (selectedFunc) { // Always check if the function exists to avoid errors const result = selectedFunc(i); console.log(result); // Output: 8 } else { console.error(`Function ${funcs[item]} not found`); } }
This approach limits function calls to only those you've explicitly defined in functionMap, eliminating the arbitrary code execution risk of eval().
Why Avoid eval()?
Just to reinforce why this matters: eval() executes any string as code. If an attacker could manipulate the funcs array or item variable, they could run malicious code in your script. The methods above prevent that by restricting which functions can be called.
内容的提问来源于stack exchange,提问作者Mike Steelson

