Make function declared in a closure global without using window
-
28-09-2019 - |
Question
How do I make a function declared in a closure, global ? This is for a google apps script, hence no window.
There is documentation on how to use closures in google apps scripts, but the example declares an object instead of a function.
http://code.google.com/googleapps/appsscript/articles/appengine.html
var JSON = JSON || {};
// foo = function(){}
(function ()
{
...
foo = function (a, b)
{
...
}
foo.prototype =
{
...
}
// window.foo = foo; // Not Possible
}());
Solution
This should work:
var globalFoo;
(function ()
{
...
foo = function (a, b)
{
...
}
foo.prototype =
{
...
}
globalFoo = foo;
// window.foo = foo; // Not Possible
}());
I've made a test in a regular html running on the browser and is works fine. Here is the example:
var globalFoo;
console.log("O1")
console.log(globalFoo);
(function(){
console.log("I1")
console.log(globalFoo);
var x = 13;
var foo = function() {
console.log('foo caled ' + x);
x++;
return true;
}
foo();
globalFoo = foo;
console.log("I2")
console.log(globalFoo);
})();
console.log("O1")
console.log(globalFoo);
console.log(globalFoo());
The firebug output to that is:
O1
undefined
I1
undefined
foo caled 13
I2
function()
O1
function()
foo caled 14
true
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow