类和对象
基本定义:
class Parent{ constructor(name='lmx'){ //name= 默认值 this.name=name } } let v_parent = new Parent('v'); console.log(v_parent); //输出Parent {name: "v"}
继承
class Parent{ constructor(name='lmx'){ this.name=name } } class Child extends Parent{ constructor(name=’child’){ super(name); //如果super中没有参数则都按照父类的默认值 } } console.log(new Child())
getter和setter
class Parent{ constructor(name='lmx'){ this.name=name } } get longName(){ return ‘mk’+this.name; } set longName( val){ this.name = val } let v = new Parent(); console.log(v.longName()) //调用get方法 v.longName = ‘hello’ //调用set方法 console.log(v.longName())
静态方法:static定义的是类的方法只有类能调用
class Parent{ constructor(name='lmx'){ this.name=name } static tell(){ console.log(‘tell’) } Parent.tell() }
静态属性:
ES6明确规定,Class内部只有静态方法,没有静态属性,但是可以通过 类名.变量 来定义
class Parent{ constructor(name='lmx'){ this.name=name } } Parent.abc=’123’
Promise
Promise.all([ ]).then() 表示把多个Promise实例当做一个Promise实例,当所有Promise实例状态发生改变之后,新的Promise才能发生改变,即当三个loadImg实例都加载完之后才会触发Promise.all方法,才会then,才执行showImg
//所有图片加载完了之后才一起显示 function loadImg(src){ return new Promise((resolve,reject)=>{ let img = document.createElement('img'); img.src= src; img.onload = function(){ resolve(img) }; img.onerror = function(){ reject(err)} }) } function showImg(imgs){ imgs.forEach(item=>{ document.body.appendChild(item) }) }; Promise.all([ loadImg('http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg'), loadImg('http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg'), loadImg('http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg') ]).then(showImg)
Promise.race ([ ]).then() 多个实例中有一个状态率先改变之后,race实例会改变,其他的便忽略不管了
//只要有图片加载出来了就显示 function loadImg(src){ return new Promise((resolve,reject)=>{ let img = document.createElement('img'); img.src= src; img.onload = function(){ resolve(img) }; img.onerror = function(){ reject(err)} }) } function showImg(imgs){ imgs.forEach(item=>{ document.body.appendChild(item) }) }; Promise.race([ loadImg('http://img02.tooopen.com/images/20150928/tooopen_sy_143912755726.jpg'), loadImg('http://img06.tooopen.com/images/20160818/tooopen_sy_175866434296.jpg'), loadImg('http://img06.tooopen.com/images/20160818/tooopen_sy_175833047715.jpg') ]).then(showImg)
Iterator接口
在数组中的应用
let arr = ['hello','world']; let map = arr[Symbol.iterator](); console.log(map.next()); console.log(map.next()); console.log(map.next()); //输出,done变为true之后循环截止
自定义iterator接口
for...of循环
let obj = { start:[3,5,6], end:[4,8,9], [Symbol.iterator](){ //iterator小写 let self= this; let index = 0; let arr = self.start.concat(self.end); let len = arr.length; return{ next(){ if(index<len){ return { value:arr[index++], done:false} }else{ return { value:arr[index++], done:true } } } } } } ; for(let key of obj){ console.log(key) }