gpt4 book ai didi

javascript - 将 JavaScript 方法移至全局范围

转载 作者:行者123 更新时间:2023-11-28 20:31:56 25 4
gpt4 key购买 nike

在 JavaScript 中,是否可以将内部函数从一个函数移至全局作用域?我还没有找到任何直接的方法来做到这一点。

function moveMethodsIntoGlobalScope(functionName){
//move all of functionName's methods into the global scope
//methodsToPutIntoGlobalScope should be used as the input for this function.
}

//I want all of the methods in this function to be moved into the global scope so that they can be called outside this function.
function methodsToPutInGlobalScope(){
function alertSomething(){
alert("This should be moved into the global scope, so that it can be called from outside the function that encloses it.");
}
function alertSomethingElse(){
alert("This should also be moved into the global scope.");
}
}

最佳答案

如果您不想在 methodsToPutInGLobalSpace 中进行更改,您可以使用以下肮脏的技巧:

var parts = methodsToPutInGlobalScope.toString().split('\n');
eval(parts.splice(1, parts.length - 2).join(''));

作为最终解决方案,我们可以使用:

moveMethodsIntoGlobalScope(methodsToPutInGlobalScope);
alertSomething(); //why doesn't this work?

function moveMethodsIntoGlobalScope(functionName){
var parts = functionName.toString().split('\n');
eval.call(window, parts.splice(1, parts.length - 2).join(''));
}

//I want all of the methods in this function to be moved into the global scope so that they can be called outside this function.
function methodsToPutInGlobalScope(){
function alertSomething(){
alert("This should be moved into the global scope, so that it can be called from outside the function that encloses it.");
}
function alertSomethingElse(){
alert("This should also be moved into the global scope.");
}
}

Live demo

关于javascript - 将 JavaScript 方法移至全局范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16198225/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com