• javascript statically scope


    在javascript 里面, 函数中使用的未定义的变量,会默认变为全局的变量。 而通过 var 这个关键字定义的变量,就是局部变量。

    As far as the output is concerned myVar and addMe both will be global variable in this case , as in javascript if you don't declare a variable with var then it implicitly declares it as global hence when you call runMe() then myVar will have the value 10 and addMe will have 20 .

    ---------------------------------------------------------------------------------------------------------------------------

    Are variables statically or dynamically “scoped” in javascript?

    Or more specific to what I need:

    If I call a function from within another function, is it going to pull the variable from within the calling function, or from the level above? Ex:

    myVar=0;
    
    function runMe(){
        myVar = 10;
        callMe();
    }
    
    function callMe(){
       addMe = myVar+10;
    }

    What does myVar end up being if callMe() is called through runMe()?

    -----------------------------------------------------------------------------------------------------

    Jeff is right. Note that this is not actually a good test of static scoping (which JS does have). A better one would be:

    myVar=0;
    
    function runMe(){
        var myVar = 10;
        callMe();
    }
    
    function callMe(){
       addMe = myVar+10;
    }
    
    runMe();
    alert(addMe);
    alert(myVar);

    In a statically scoped language (like JS), that alerts 10, and 0. The var myVar (local variable) in runMe shadows the global myVar in that function. However, it has no effect in callMe, so callMe uses the global myVar which is still at 0.

    In a dynamically scoped language (unlike JS), callMe would inherit scope from runMe, so addMe would become 20. Note that myVar would still be 0 at the alert, because the alert does not inherit scope from either function.

  • 相关阅读:
    C#UDP编程总结
    C# TcpListener的编程要点
    三维地图添加切片“lods of null”报错
    三维地图添加切片图层坐标系报错
    03 三维地图添加切片图层
    从ArcMap 10.6.1发布服务到Portal,服务器地址错误
    19 React——Ant Design(按需加载样式文件)
    20 React项目生成及部署
    18 React——Ant Design的使用
    17 React——路由的模块化及嵌套
  • 原文地址:https://www.cnblogs.com/oxspirt/p/7986720.html
Copyright © 2020-2023  润新知