调用在JavaScript函数作为全局函数

问题描述:

我在javascript中有一个主要功能是功能的(){这里的一些代码},我也有,看起来像调用在JavaScript函数作为全局函数

function a() { 

    function b() { 

     // some code here 
    } 

} 

这个主要功能的子功能现在我想直接调用函数b。那么如何做到这一点。

+0

声明函数的函数。多么乖乖!;)难道你不能简单地剪切/粘贴b()使它与()(全局脚本级别,因此是全局可见性)在同一级别上吗? – 2012-03-26 05:43:00

你可以尝试明确地暴露b全局对象像这样的:

function a() { 

    function b() { 

     // some code here 
    } 

    window.exposed = b; 
} 
+0

如果主机环境没有窗口对象? – RobG 2012-03-26 08:07:28

不要声明函数B的功能里面,只是把它像这样

function b() { 
some code here 
} 

function a() { 
b(); 
} 
+0

这是一个明显的答案,但它缺少关于如何从'b'访问'a'的当地人的讨论,即如何提取'a'的当地人以使封闭等价。 – 2012-03-26 05:40:17

+0

为什么不把它正确地编码?全球呼叫您的全球通。 – user1289347 2012-03-26 06:09:41

你不能。不过你可以这样做:

function a() { 

    this.b = function() { 

     some code here 
    } 
} 

然后调用它像:

var x = new a(); 
a.b(); 

您还可以创建一个对象文本与功能:

var a = { 
    b: function() 
    { 
     //some code here 
    } 
}; 

然后只是说:

a.b(); 

你也可以创建函数对象本身的属性,并访问它的方式:

function a() 
{ 
}; 

a.b = function() 
{ 
    //Some code here 
}; 

然后用叫它:

a.b(); 

这里有很多的解决方案,是唯一一个我认为这将是西装的功能附加到全局对象,所以它看起来像一个DECL ared函数。唯一的区别是,它不会使用,直到a运行:

function a() { 

    // Protect against ES5 strict mode, assume function is called as global code 
    if (typeof this !== undefined) { 
    this.b = function() { /* whatever */ }; 
    } 
} 

或许以下适合您的编码风格更好:

function a() { 

    function b() { /* whatever */}; 

    if (typeof this !== undefined) { 
    this.b = b; 
    } 
} 

简称为:

a(); 

然后在ES3或ES5非严格模式,它将按预期工作。为了克服ES5严格的限制,其中上述将导致的是不确定的,叫一个作为全局代码,并设置其明确:

a.call(this); 

或其它一些适合的参照全局对象。

我已经使用窗口敬而远之,因为这是不可靠的,不只是因为非浏览器的主机可能不会有窗口对象。