使函数在闭包全局中声明而不使用窗口 [英] Make function declared in a closure global without using window

查看:124
本文介绍了使函数在闭包全局中声明而不使用窗口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在闭包中声明全局函数?这是一个谷歌应用程序脚本,因此没有窗口



有关如何在Google应用程序脚本中使用闭包的文档,声明一个对象而不是一个函数。
http://code.google.com/googleapps/appsscript/articles /appengine.html

var JSON = JSON || {};



$ p $ // foo = function(){}
(function()
{
...

foo =函数(a,b)
{
...
}

foo.prototype =
{
...
}

// window.foo = foo; //不可能
}());


解决方案



  var globalFoo; 

(函数()
{
...

foo =函数(a,b)
{
。 ..
}

foo.prototype =
{
...
}

globalFoo = foo;
// window.foo = foo; //不可能
}());

我在浏览器上运行的常规html中做了测试,工作正常。这里是例子:

  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 ++;
返回true;
}

foo();

globalFoo = foo;

console.log(I2)
console.log(globalFoo);
})();

console.log(O1)
console.log(globalFoo);
console.log(globalFoo());

萤火虫输出为:

 









$ b $
函数()
foo caled 14
true


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
}());

解决方案

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

这篇关于使函数在闭包全局中声明而不使用窗口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆