问题
Consider this code:
(function a() {
// Nested function
function b() {
console.log("Works!");
}
b();
})();
This code works, but would it be possible (in theory) to call b()
if the name is inside a string (i.e. dynamic)?
If b()
would be declared in the global scope, we could use window[stringContainingName]();
. Is there a possibility in this case?
This is only a theoretical question! I know that such code is bad design.
回答1:
This code works, but would it be possible (in theory) to call b() if the name is inside a string (i.e. dynamic)?
No, function declaration has the same rules for scope, so it's not possible even in theory (unless we talk about closures, of course).
If b() would be declared in the global scope, we could use windowstringContainingName; Is there a possibility in this case?
Yes, of course: this...
(function a() {
// Nested function
window.b = function() {
console.log("Works!");
}
b();
})();
b(); // or window['b'](), or window.b()
... will log 'Works'
twice. I used explicit global object here, as in the strict mode direct assignment to b
without declaring it (using b = function() ...
instead of window.b = function() ...
) will cause ReferenceError.
回答2:
Is there a possibility in this case?
Only by making the b
function a property of an object:
(function a(name) {
var fns = {
b: function b() {
console.log("Works!");
}
};
// possibly secure by `if (fns.hasOwnProperty(name))`
fns[name]();
})("b");
You will need to know the names of the functions in beforehand.
来源:https://stackoverflow.com/questions/18764657/call-nested-function-with-dynamic-name