2013-04-24 10 views
0

В JavaScript можно ли перемещать внутренние функции из одной функции в глобальную область? Я еще не нашел простого способа сделать это.Переместить 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."); 
    } 
} 
+0

Это невозможно, вы можете сделать 'методыToPutInGlobalScope' объектом вместо функции, а затем y ou сможет получить доступ к функциям внутри него. – Dfr

+0

Имеет ли 'методыToPutInGlobalScope' только объявления функций внутри него или есть еще? Например, использование eval * может * работать, но может и не быть тем, что вы хотите, если внутри функции больше, чем декларации функций. –

ответ

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

Live demo

+0

Этот ответ по-прежнему не объясняет, как реализовать «moveMethodsIntoGlobalScope», что я и пытаюсь сделать в первую очередь. –

+0

Нет никакого тривиального способа сделать это. Я думаю, вам нужно проанализировать 'moveMethodsIntoGlobalScope' (используйте' moveMethodsIntoGlobalScope.toString() ', чтобы получить строковое представление), и после этого объявите внутренние функции в глобальной области. –

+0

На самом деле есть! Я отредактирую свой ответ через некоторое время. –

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(); 
+0

Когда вызывается 'methodsToPutIntoGlobalScope', кажется, что он не перезаписывает ранее существовавшие функции.Есть ли способ обойти эту проблему? http://jsfiddle.net/5CC52/9/ –

+0

Странно. Это будет работать 'window [" alertSomething "]();'. Похоже, вызов метода привязан к оригиналу, но непрямой вызов метода будет работать. –

+0

Он работает с 'eval', как и ответ от @Minko Gechev - http://jsfiddle.net/fiddlegrimbo/5CC52/12/ –

0

Да, это возможно. Если вы объявляете переменную с использованием ключевого слова var, эта переменная становится только локальной, но если вы ее не сделаете, она станет глобальной.

function foo(){ 

    var test = 'test'; // <- Using var keyword 
} 

foo(); // <- execute the function 

console.log(test); // undefined 

Но если мы делаем то же самое без var ключевого слова:

function foo(){ 

    test = 'test'; // <- Using var keyword 
} 

foo(); // <- execute the function 

console.log(test); // test 

Для того, чтобы сделать ваши внутренние функции глобального, вы бы объявить анонимные функции без var ключевого слова

function methodsToPutInGlobalScope() { 

    alertSomething = function() { 
     alert("This should be moved into the global scope, so that it can be called from outside the function that encloses it."); 
    } 

    alertSomethingElse = function() { 
     alert("This should also be moved into the global scope."); 
    } 

} 


methodsToPutInGlobalScope(); // <- Don't forget to execute this function 


alertSomething(); // Works 
alertSomethingElse(); // Works as well 
Смежные вопросы