简体   繁体   English

如何在Javascript中从外部范围调用函数?

[英]How to call a function from outer scope in Javascript?

Consider the code: 考虑一下代码:

function foo()
{
    console.log('foo');
}

function bar()
{
    var foo = 5;
    foo(); // (*)
}

How to make (*) refer to outer function instead of local variable? 如何使(*)引用外部函数而不是局部变量?

If the outer scope is the global scope, you can do 如果外部范围是全局范围,则可以执行

window.foo(); // assuming you're in a browser

If not, then you're out of luck. 如果没有,那你就不走运了。 Give the local variable another name. 给局部变量起另一个名字。

An example of when you're out of luck: 一个不走运的例子:

window.onload = function() {
    function foo()
    {
        console.log('foo');
    }

    function bar()
    {
        var foo = 5;
        foo(); // (*)
    }
}

The scope of the anonymous "load" handler function has no name, or any other handle by which the code in function "bar" could indicate that it wanted a reference to that "foo" instead of the local one. 匿名“加载”处理程序函数的范围没有名称,或任何其他句柄,函数“ bar”中的代码可以通过该句柄指示其希望引用 “ foo”而不是本地引用。

Note that Coffeescript explicitly disallows this; 注意,Coffeescript明确禁止这样做; it won't allow a local symbol to hide a more global one. 它不允许本地符号隐藏更全局的符号。 (That's a controversial feature of the language , before you jump on the Coffeescript train.) (这是该语言的一个有争议的功能 ,在您跳上Coffeescript火车之前。)

If your function is global you can use: 如果您的函数是全局函数,则可以使用:

window.foo()

More info: http://www.w3schools.com/js/js_function_invocation.asp 更多信息: http : //www.w3schools.com/js/js_function_invocation.asp

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM