interview-answe icon indicating copy to clipboard operation
interview-answe copied to clipboard

184.变量提升

Open webVueBlog opened this issue 5 years ago • 4 comments

[js]

webVueBlog avatar Apr 15 '20 22:04 webVueBlog

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

webVueBlog avatar Apr 15 '20 22:04 webVueBlog

bla = 2
var bla;
// ...

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

var bla;
bla = 2;

webVueBlog avatar Apr 15 '20 22:04 webVueBlog

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 avatar Apr 15 '20 22:04 webVueBlog

声明并初始化两个变量:
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' 才出现了这样的结果。

webVueBlog avatar Apr 15 '20 22:04 webVueBlog