Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript 变量提升与函数提升 #41

Closed
PolluxLee opened this issue Jun 8, 2018 · 0 comments
Closed

JavaScript 变量提升与函数提升 #41

PolluxLee opened this issue Jun 8, 2018 · 0 comments

Comments

@PolluxLee
Copy link
Owner

PolluxLee commented Jun 8, 2018

# 变量声明提升

  1. 变量提升会把变量声明提升到全局作用域或函数作用域顶端
  2. 变量提升只提升声明,而不提升初始化

1)

var x = 1;                 // 声明 + 初始化 x
console.log(x + " " + y);  // '1 undefined'
var y = 2;                 // 声明 + 初始化 y

//上面的代码和下面的代码是一样的 
var x = 1;                 // 声明 + 初始化 x
var y;                     //声明 y
console.log(x + " " + y);  //y 是未定义的
y = 2;                     // 初始化  y 

变量提升只提升声明,而不提升初始化。y 变量的初始化是在 log 之后,所以 log 会打印 undefined

2)

var foo = 3;
function bar() {
    var foo = foo || 5;
    console.log(foo); // 5
}
bar();

// 相当于
var foo = 3;
function bar() {
    var foo;
    foo = foo || 5;
    console.log(foo);  // 5
}
bar();

foo 被提升到函数作用域顶端,foo || 5 得到的结果就是 5,而屏蔽了 global 中的 foo

# 函数声明提升

  1. 函数提升仅适用于函数声明,而不适用于函数表达式,即,形如,function foo() {} 才可以,而 var foo = function() {} 不能被提升
  2. 函数提升是为了解决两个函数相互递归调用的问题

1)

console.log(square(5));  //  25
/* ... */
function square(n) { return n*n }

2)

function bar() {
    foo(); // 2
    var foo = function() {
        console.log(1);
    };
    foo(); // 1
    function foo() {
        console.log(2);
    }
    foo(); // 1
}
bar();

//  相当于
function bar() {
    var foo;
    function foo() {
        console.log(2);
    }
    foo(); // 2
    foo = function() {
        console.log(1);
    };
    foo(); // 1
    foo(); // 1
}
bar();

# let 和 const 关键字

在 ES6 之前,只有全局作用域与函数作用域,而没有块级作用域。在 ES6 中,let 和 const 关键字为 JavaScript 增加了块级作用域

1)

function f1() {
  let n = 5;
  if (true) {
    let n = 10;
  }
  console.log(n); // 5
}

f1();

2)

function f1() {
  const MAX = 6;
  if (true) {
    const MAX = 10;
  }
  console.log(MAX); // 6
}

f1();

3)不会变量提升

function do_something() {
  console.log(bar); // undefined
  console.log(foo); // ReferenceError: foo is not defined
  var bar = 1;
  let foo = 2;
}

4)暂时性死区

由于词法作用域,表达式(foo + 55)内的标识符“foo”会解析为if块的foo,而不是覆盖值为33的foo。在这一行中,if块的“foo”已经在词法环境中创建,但尚未达到(并终止)其初始化(这是语句本身的一部分):它仍处于暂存死区

function test(){
   var foo = 33;
   if (true) {
      let foo = (foo + 55); // ReferenceError
   }
}
test();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant