13 class和module
①export和import
profile.js
export var firstName = 'David';
export var lastName = 'Belle';
export var year = 1973;
//等价于
var firstName = 'David';
var lastName = 'Belle';
var year = 1973;
export { firstName , lastName , year}
引用
import {firstName, year} from './profile'
②给export的属性或方法使用默认名称:
export default function foo() { console.log('foo')}
引用
import xx from './export-default.js';
xx();// 'foo'
③模块继承
circleplus.js
export * from 'circle';// 输出circle模块所有属性方法
export default ...
export { xx } from 'circle'
main.js
module math from 'circleplus';
import exp from 'circleplus';// 默认方法命名为exp
// lib.js
export let counter = 3;
export function incCounter() {
counter++;
}
// main.js
import { counter, incCounter } from './lib';
console.log(counter); // 3
incCounter();
console.log(counter); // 4
12 promise
基本用法
var promise = new Promise(function(resolve, reject){
if(//成功) resolve(value);
else reject(error) ;
})
promise.then(
function(value){// success} ,
function(value){ // failure}
) ;
链式操作:返回新的Promise对象,后一个回调函数等待它有了结果,才进一步调用
catch是then(null,rejection)的别名,“冒泡”向后传递直至被捕获
xx.then( //dsf ).then( //xxx ).catch(
error => {console.log(error);}
);
Promise.all(promises).then(//xx).catch(//xxx)将多个异步操作或者Promise对象包装秤一个新的Promise对象,等所有执行完成后,该对象fuflled
Promise.resolve将对象转换为Promise对象,如果参数不具有then方法,新Promise对象状态为resolved
async function xx(){//xxx}表示函数体内有异步操作,会先返回等待异步执行完毕,继续执行体内剩下的操作
11 generator函数
就是一个普通函数,但是包含一个内部状态遍历器,可以依次遍历状态。特征是function*后面跟着一个*号,用yield语句定义不同状态,或者说不同成员
function* hello(){
yield 'hello';
yield 'world';
return 'ending' ;
}
var a = new hello();
a.next().next().next()
应用
function* loadUI() {
showLoadingScreen();
yield loadUIDataAsynchronously() ;
hideLoadingScreen();
}
var loader = loadUI();
loader.next();// 加载UI
loader.next();// 卸载UI
yield*语句,语法表明它返回一个遍历器
let delegatedIterator = (function* () {
yield 'hello' ;
yield 'bye''
}());
let delegatingIterator = (function* () {
yield 'before;'
yield* delegatedIterator;
yield 'after';
}())
for(let value of delegatingIterator ) {
console.log(value) ;
}
还有遍历完全二叉树
10 Iterator和for of循环
部署了next()方法的对象,就有了遍历器功能,next方法包含value,done两个属性的对象
function makeIterator(array) {
var nextIndex = 0;
return {
next: function(){
return nextIndex < array.length ?
{value: array[nextIndex++], done:false} :
{value: undefined, done:true}
}
}
}
for in获取键名,for of获取键值
9 set和map
Set()唯一不重复的数组,add delete has clear
Map(),js对象只能用字符串做键,Map可以用字符串、对象做键;set(k, v)
WeakMap() 只接受对象作为键名,键对应的对象未来可能消失,防止内存泄漏
8 函数扩展
默认值; 。。。; =》
7 对象扩展
Object.is() assgn(target, source1...)
可以表达式作为对象键,要把表达式放在方括号内
var a = 'xdfs';
var obj = {
"ddf" : "asdf",
[a] : "sdfdfd"
}
Symbol()类型,独一无二不相等
Proxy()拦截,可以类似于AOP做拦截器
Object.observe(obj, observeFunction);
全部来自于阮一峰ECMAScript6入门