es6 新特性
let const
class, extends, super
ES6的继承机制,实质是先创造父类的实例对象this(所以必须先调用super方法),然后再用子类的构造函数修改this。
constructor内定义的方法和属性是实例对象自己的,而constructor外定义的方法和属性则是所有实力对象可以共享的。
下面定义了一个Cat类,该类通过extends关键字,继承了Animal类的所有属性和方法。
super关键字,它指代父类的实例(即父类的this对象)。子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。
class Animal { constructor(){ this.type = 'animal' } says(say){ console.log(this.type + 'says ' + say) } } let animal = new Animal() animal.says('hello') //animal says hello class Cat extends Animal { constructor(){ super() this.type = 'cat' } } let cat = new Cat() cat.says('hello') //cat says hello
arrow function 箭头函数
class Animal { constructor(){ this.type = 'animal' } says(say){ setTimeout( () => { console.log(this.type + ' says ' + say) }, 1000) } } var animal = new Animal() animal.says('hi') //animal says hi
箭头函数没有自己的this,它的this是继承外面的,因此内部的this就是外层代码块的this。
destructuring 解构
从数组和对象中提取值,对变量进行赋值
let cat = 'ken' let dog = 'lili' let zoo = {cat, dog} console.log(zoo) //Object {cat: "ken", dog: "lili"} let dog = {type: 'animal', many: 2} let { type, many} = dog console.log(type, many) //animal 2
default, rest
function animal(type = 'cat'){ console.log(type) } animal() function animals(...types){ console.log(types) } animals('cat', 'dog', 'fish') //["cat", "dog", "fish"]
Promise
ES6 规定,Promise对象是一个构造函数,用来生成Promise实例。
let promise = new Promise(function(resolve, reject) {
console.log('Promise');
resolve();
});
promise.then(function() {
console.log('Resolved.');
});
console.log('Hi!');
// Promise
// Hi!
// Resolved
Promise 新建后立即执行,所以首先输出的是Promise。然后,then方法指定的回调函数,将在当前脚本所有同步任务执行完才会执行,所以Resolved最后输出。
promise 好复杂。。。。未完待续。。。