简体   繁体   English

嵌套函数作用域变量

[英]Nested function scope variable

I'm using this doc : http://www.w3schools.com/js/js_scope.asp as an exemple. 我正在使用此文档: http : //www.w3schools.com/js/js_scope.asp作为示例。

I'm trying to get var name = snoopdog, outside the main function. 我正在尝试在主要功能之外获取var name = snoopdog。

 function A(){ function B(){ name = "snoopdog"; } //Show snoopdog alert(name); } //Show nothing alert(name); 

Ok I tried to put the nested function inside a variable, still not working. 好的,我试图将嵌套函数放入变量中,但仍然无法正常工作。

Global variables to the rescue 拯救全局变量

var name;
A();
alert(name) //shows snoopdog

function A(){
    B();

      function B(){
      name = "snoopdog";  
    }
    //Show snoopdog
    alert(name);
}

Using a var outside the main function, means you want to put it on the 'window' scope. 在main函数之外使用var意味着您要将其放在“ window”范围内。

function A() {
    function B() {
        window.name = "snoopdog";  
    }
    //Show snoopdog
    alert(window.name);
}
//Show nothing
alert(window.name);

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

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