声明提前(hoisting)

2019-04-12  本文已影响0人  shijiatongxue

在JavaScript中,在函数内声明的所有变量在函数体内始终是可见的。变量甚至在声明之前已经可用。这个特性被非正式地称为声明提前,即JS函数里声明的所有变量都被“提前”至函数的顶部。

一个例子✍:

var scope = "global";
function f(){
  console.log(scope); // 不输出"global"
  var scope = "local";
  console.log(scope);
}

第一个log()方法不会搜索到全局的变量“scope”,并打印“global”,由于声明提前,上面代码相当于:

var scope = "global";
function f(){
  var scope; // 变量提前至所在作用域的顶部
  console.log(scope); // >>= "undefined"
  scope = "local";
  console.log(scope); // >>= "local"
}

来源:JavaScript权威指南

上一篇 下一篇

猜你喜欢

热点阅读