11.Generator函数
一个内部状态的遍历器,即每调用一次遍历器,内部状态就发生一次改变。
特征:function关键字后面有个星号;函数体内部使用yield语句定义遍历器的每个成员,即不同的内部状态。
例:function* helloWorldGenerator() {
yield 'hello';
yield 'world';
return 'ending';
}
var hw = helloWorldGenerator();
hw.next() //{value: 'hello', done: false}
hw.next() //{value: 'world', done: false}
hw.next() //{value: 'ending', done: true}
hw.next() //{value: undefined, done: true}
12.Promise对象
一个构造函数,用来生成Promise实例。
例:var promise = new Promise(function(resolve, reject){
if(/*异步操作成功*/){
resolve(value);
} else{
reject(error);
}
});
promise.then(function(value){
//success
},
function(value){
//failure
});
13.Class和Module
通过class关键字,可以定义类。
例:class Point {
constructor(x,y) {
this.x = x;
this.y = y;
}
toString() {
return '(' + this.x + ',' + this.y + ')';
}
}
var point = new Point(2,3);
point.toString(); //(2,3)
Module为模块功能
关键字:export和import
例:
//circle.js
export function area(radius) {
return Math.PI * radius * radius;
}
export function circumference(radius) {
return 2 * Math.PI * radius;
}
//main.js
import { area, circumference } from 'circle';
console.log("圆面积:" + area(4));
console.log("圆周长:" + circumference(14));