0

JavaScript では、内部関数を 1 つの関数からグローバル スコープに移動できますか? これを行う簡単な方法をまだ見つけていません。

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.");
    }
}
4

3 に答える 3

2

変更を加えたくない場合は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.");
    }
}

ライブデモ

于 2013-04-24T17:16:04.600 に答える
1

あまり洗練されていませんが、機能します。

function copyInto(arr, context) {
    //move all of functionName's methods into the global scope
    //methodsToPutIntoGlobalScope should be used as the input for this function.
    for (var i = 0; i < arr.length; i += 2) {
        var exportName = arr[i];
        var value = arr[i + 1];
        eval(exportName + "=" + value.toString());
    }
}

//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.");
    }

    copyInto(["alertSomething", alertSomething, "alertSomethingElse", alertSomethingElse], window);
}

methodsToPutInGlobalScope();
alertSomething();
alertSomethingElse();
于 2013-04-24T17:29:53.623 に答える