什么是颞盲区?

2020/11/02 08:02 · javascript ·  · 0评论

我听说,在初始化之前访问letconst值可能会ReferenceError由于称为“临时死区”原因而导致这种情况

什么是时间盲区,它与范围和起重有何关系,在什么情况下会遇到?

let与以下内容const有两个主要区别var

  1. 它们是块作用域的
  2. var在声明之前访问a会产生结果undefined在声明之前访问aletconstthrows ReferenceError
console.log(aVar); // undefined
console.log(aLet); // causes ReferenceError: aLet is not defined
var aVar = 1;
let aLet = 2;

从这些示例中可以看出,let声明(和const,以相同的方式工作)可能不会被吊起,因为aLet在赋值之前似乎并不存在。

这不是的情况下,however-letconst 悬挂(如varclassfunction),但有输入范围和所声明,他们不能被访问之间的时段。该时间段是时间盲区(TDZ)

该TDZ结束时aLet宣布,而不是分配

//console.log(aLet)  // would throw ReferenceError

let aLet;
console.log(aLet); // undefined
aLet = 10;
console.log(aLet); // 10

此示例显示了如何let吊起:

let x = 'outer value';
(function() {
  // start TDZ for x
  console.log(x);
  let x = 'inner value'; // declaration ends TDZ for x
}());

来源:神秘的时间死区(TDZ)

x在内部范围内访问仍会导致ReferenceError如果let不悬挂,它将记录outer value

TDZ是一件好事,因为它有助于突出显示错误-很少在声明之前访问值。

TDZ也适用于默认函数参数。从左到右对参数进行求值,每个参数在TDZ中直到被分配:

// b is in TDZ until its value is assigned
function testDefaults(a=b, b) { }
testDefaults(undefined, 1); // throws ReferenceError because the evaluation of a reads b before it has been evaluated.

babel.js编译器默认未启用TDZ 打开“高合规性”模式以在REPL中使用它提供es6.spec.blockScoping标志以与CLI一起使用或作为库使用。

推荐进一步阅读:TDZ揭开神秘面纱ES6 Let,Const和“深度死区”(TDZ)深入

Hoisting:
let,const,var are all get hoisted process.
(whats mean they go upper and declare in the top of the scope.)

Initialisation:

  • var go also through the initial process, and get initial value of undefined.
  • while let,const didn't go throw the initial process, so their values are still inaccessible, although they already declared.
    whats put them in temporal dead zone

So in shortly:

hoisting process: var, let, const
Initialisation process:
var

In case of let and const variables, Basically, Temporal Dead Zone is a zone

"before your variable is declared",

i.e where you can not access the value of these variables, it will throw an error.

ex.

let sum = a + 5;        //---------
//some other code       //         | ------>  this is TDZ for variable a
                        //         |
console.log(sum)        //---------
let a = 5;

above code gives an error

the same code will not give an error when we use var for variable 'a',

ex.

var sum = a;                            
console.log(sum)     //prints undefined
var a = 5;
本文地址:http://javascript.askforanswer.com/shenmeshiniemangqu.html
文章标签: ,   ,   ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!

文件下载

老薛主机终身7折优惠码boke112

上一篇:
下一篇:

评论已关闭!