ES6主要特性汇集及解释
1、let,const:块作用域(相对于函数作用域,全局作用域而出现)
var a = [];
for (var i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6]();
// 10
var a = [];
for (let i = 0; i < 10; i++) {
a[i] = function () {
console.log(i);
};
}
a[6](); // 6
2、class,extends,super:基于原生JS原型链中this指针混乱而设计,构造函数constructor
3、arrow functions:箭头函数,解决this指向不明问题
es5: function(1){return i++;}
es6: (i) => i++
4、template string:模版字符串,解决JS代码变量与字符串混编问题,
eg:
var name = 'jack'
var hello = `hello ${name}`
5、destructuring:解构赋值
es5:
let cat = 'ken' let dog = 'lili'
let zoo = {cat: cat, dog: dog}
console.log(zoo) //Object {cat: "ken", dog: "lili"}
es6:
let cat = 'ken' let dog = 'lili'
let zoo = {cat, dog}
console.log(zoo) //Object {cat: "ken", dog: "lili"}
OR:
let dog = {type: 'animal', many: 2}
let { type, many} = dog
console.log(type, many) //animal 2
6、default:默认值
es5:
function animal(type){ type = type || 'cat' console.log(type) } animal()
es6:
function animal(type = 'cat'){ console.log(type) } animal()
7、rest arguments
function animals(...types)
{
console.log(types)
}
animals('cat', 'dog', 'fish') //["cat", "dog", "fish"]
function test(a1,a2,a3){
console.log(a1,a2,a3)
}
let a = [1,2,3]
test(...a) //1 2 3