hangzz / hangzz.github.io

:anguished:
0 stars 0 forks source link

ES6:1 #5

Open hangzz opened 7 years ago

hangzz commented 7 years ago

暂时性死区

在let或const命令声明的变量之前,该变量都是不可用的。语法上,称为“暂时性死区”(temporal dead zone,简称 TDZ)

暂时性死区

typeof x;  // ReferenceError
let x;

作为比较,如果一个变量根本没有被声明,使用typeof反而不会报错。

typeof x  // "undefined"

const保存Object指针,通过Object.freeze才能冻结对象,阻止添加属性,对象的属性是对象的,也应冻结

var constantize = (obj) => {
  Object.freeze(obj);
  Object.keys(obj).forEach( (key, i) => {
    if ( typeof obj[key] === 'object' ) {
      constantize( obj[key] );
    }
  });
};

let const 声明的挂载在全局,不等于顶层window

考虑到ES5、ES6在环境导致的行为差异太大,应该避免在块级作用域内声明函数。如果确实需要,也应该写成函数表达式,而不是函数声明语句。

解构赋值

数组解构

let [head, ...tail] = [1, 2, 3, 4];
head //1 
tail    // [2,3,4]

对象解构

var node = { loc: { start: { line: 1, column: 5 } } };
var { loc: { start: { line }} } = node;
line   // 1
loc    // error: loc is undefined
start // error: start is undefined

对象的扩展

let arr = [1, 2, 3];
let {0 : first, [arr.length - 1] : last} = arr;
first  //1
last  // 3

字符串解构

const [a, b, c, d, e] = 'hello';
let {length : len1} = 'hello';
let {length : len2} = [1,2,3,4,5]
len1 // 5
len2 //5