Skip to content

185.隐式全局变量和外部函数作用域 #185

Open
@webVueBlog

Description

@webVueBlog

[js]

Activity

webVueBlog

webVueBlog commented on Apr 15, 2020

@webVueBlog
MemberAuthor

看起来像是隐式全局作用域的变量也有可能是其外部函数变量的引用。

webVueBlog

webVueBlog commented on Apr 15, 2020

@webVueBlog
MemberAuthor
var x = 0;  // x是全局变量,并且赋值为0。

console.log(typeof z); // undefined,因为z还不存在。

function a() { // 当a被调用时,
  var y = 2;   // y被声明成函数a作用域的变量,然后赋值成2。

  console.log(x, y);   // 0 2 

  function b() {       // 当b被调用时,
    x = 3;  // 全局变量x被赋值为3,不生成全局变量。
    y = 4;  // 已存在的外部函数的y变量被赋值为4,不生成新的全局变量。
    z = 5;  // 创建新的全局变量z,并且给z赋值为5。 
  }         // (在严格模式下(strict mode)抛出ReferenceError)

  b();     // 调用b时创建了全局变量z。
  console.log(x, y, z);  // 3 4 5
}

a();                   // 调用a时同时调用了b。
console.log(x, z);     // 3 5
console.log(typeof y); // undefined,因为y是a函数的本地(local)变量。
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @webVueBlog

        Issue actions

          185.隐式全局变量和外部函数作用域 · Issue #185 · weekCodeing/interview-answe