Skip to content

184.变量提升 #184

Open
Open
@webVueBlog

Description

@webVueBlog

[js]

Activity

webVueBlog

webVueBlog commented on Apr 15, 2020

@webVueBlog
MemberAuthor

由于变量声明(以及其他声明)总是在任意代码执行之前处理的,所以在代码中的任意位置声明变量总是等效于在代码开头声明。这意味着变量可以在声明之前使用,这个行为叫做“hoisting”。“hoisting”就像是把所有的变量声明移动到函数或者全局代码的开头位置。

webVueBlog

webVueBlog commented on Apr 15, 2020

@webVueBlog
MemberAuthor
bla = 2
var bla;
// ...

// 可以隐式地(implicitly)将以上代码理解为:

var bla;
bla = 2;
webVueBlog

webVueBlog commented on Apr 15, 2020

@webVueBlog
MemberAuthor
function do_something() {
  console.log(bar); // undefined
  var bar = 111;
  console.log(bar); // 111
}

// is implicitly understood as: 
function do_something() {
  var bar;
  console.log(bar); // undefined
  bar = 111;
  console.log(bar); // 111
}
webVueBlog

webVueBlog commented on Apr 15, 2020

@webVueBlog
MemberAuthor
声明并初始化两个变量:
var a = 0, b = 0;
给两个变量赋值成字符串值:
var a = "A";
var b = a;

// 等效于:

var a, b = a = "A";
留意其中的顺序:

var x = y, y = 'A';
console.log(x + y); // undefinedA
在这里,x  y 在代码执行前就已经创建了,而赋值操作发生在创建之后。当"x = y"执行时,y 已经存在,所以不抛出ReferenceError,并且它的值是'undefined'。所以 x 被赋予 undefined 值。然后,y 被赋予'A'。于是,在执行完第一行之后,x === undefined && y === 'A' 才出现了这样的结果。
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

          184.变量提升 · Issue #184 · weekCodeing/interview-answe