es6学习6:一些新特性的实例练习
// 先定义一个简化输出函数 window.print = function (oper, result) { result ? console.log(oper, '=>', result) : console.log(oper); }
1.------------------proxy------------------------
// 设置一个msg用来检测上次操作是否成功变更 let msg = {status: 0, content: ''}; // 设置proxy验证规则 var studentValid = { get: function (target, key) { msg.status = 0; if (key in target) { return target[key]; } return '无相关记录'; }, set: function (target, key, newValue) { msg.status = 0; let oldValue = target[key]; if (!(key in target)) { msg = '无相关属性..'; return '^_^'; } if (mm.isEqual(oldValue, newValue)) { msg = '名称相同, 无需更改'; return '^_^'; } if (key === 'name' && !/[A-Za-z]+/.test(newValue)) { throw new Error('值类型错误'); return '^_^'; } if (key === 'name' && (newValue.length === 1 || newValue.length > 6)) { throw new Error('长度设置错误..'); return '^_^'; } if (key === 'age' && (newValue <= 0)) { throw new Error('值范围设置错误..'); return '^_^'; } msg = {status: 1, content: `key: ${key} 更改为${newValue}`}; target['up_date'] = Date(); return target[key] = newValue; }, has(target, key) { if (key === 'up_date') { return false; } return ' '; }, deleteProperty(target, key) { if (/^_/.test(key)) { msg = {status: 1, content: `删除了${key}属性`}; target['up_date'] = Date(); return delete target[key]; } return true; } }; // 代理模式处理数据 let student_1_orgin = {name: 'avenda', age: '24', up_date: Date(), _deleteProp: 'test'}, student_1 = new Proxy(student_1_orgin, studentValid); delete student_1._deleteProp; print(student_1_orgin, msg);
2.------------------class每New一个对象产生一个新的序号------------------------
let authorDefault = { name: 'avenda', age: 25 } class Father { constructor(name = "father") { this.data = { name: name, author: authorDefault } } } class Son extends Father { constructor(status = 0, msg = '') { super(); if (!Son.vol) { Son.vol = 0 } // 指定初始版本号为0 this.data.vol = Son.vol++; // 对象版本号 this.data.status = status; this.data.msg = msg; } static creatSonByErrorMsg(msg) { return new Son(0, msg).data; } static creatSonByError() { return new Son(0).data; } static creatSonBySuccess() { return new Son(1).data; } static creatSonBySuccessMsg(msg) { return new Son(1, msg).data; } } var son = Son.creatSonBySuccessMsg('创建成功'); var son2 = Son.creatSonBySuccessMsg('创建成功'); var son3 = Son.creatSonBySuccessMsg('创建成功'); print('sucson', son); print('vol', son3.vol)
3.------------------Promise串行(比较麻烦的方法)------------------------
let [a, b, d] = [true, true, true]; let promiseA = new Promise((resolve, reject) => { setTimeout(() => { if (a) { resolve(() => { print('promise', 'A') }); } else { reject('A执行错误'); } }, 1000) }); let promiseB = new Promise((resolve, reject) => { setTimeout(() => { if (b) { resolve(() => { print('promise', 'B') }); } else { reject('B执行错误'); } }, 1000) }); let promiseC = new Promise((resolve, reject) => { setTimeout(() => { if (d) { resolve(() => { print('promise', 'C') }); } else { reject('C执行错误'); } }, 1000) });
4.------------------Promise串行(比较方便的方法)------------------------
let [a, b, d] = [true, true, true]; let promiseA = new Promise((resolve, reject) => { setTimeout(() => { if (a) { resolve(() => { print('promise', 'A') }); } else { reject('A执行错误'); } }, 1000) }); let promiseB = new Promise((resolve, reject) => { setTimeout(() => { if (b) { resolve(() => { print('promise', 'B') }); } else { reject('B执行错误'); } }, 1000) }); let promiseC = new Promise((resolve, reject) => { setTimeout(() => { if (d) { resolve(() => { print('promise', 'C') }); } else { reject('C执行错误'); } }, 1000) }); Promise.all( [promiseA,promiseB,promiseC] ).then((result)=>{ // result是对应的promiseA-C的resolve参数 result.forEach(item=>item()) print('全部执行完成...'); },(msg)=>{ // 执行到某步错误时候对应的reject print(msg) })
5.------------------模拟迭代器原理写个对象迭代器代理(让对象像数组一样操作, 并像java迭代器一样迭代)----------------------
function iteratorProxy (target) { let _index = 0; let keys = Object.keys(target); let len = keys.length; let loop = false; return { next() { this.indexFilter(); if (_index < len - 1 && _index >= 0) { return { key: keys[_index], value: target[keys[_index++]], done: false } } else { try { return { key: keys[_index], value: target[keys[_index++]], done: true } } finally { if(loop){ _index = 0; } } } }, pre() { this.indexFilter(); if (_index < len && _index >= 0) { return { key: keys[_index], value: target[keys[_index--]], done: false } } else { loop ? _index = len - 1 : ''; return { key: keys[_index], value: target[keys[_index--]], done: true } } }, hasNext() { return _index < len; }, hasPre() { return _index >= 0; }, get(index = _index) { this.indexFilter(); return (index >= 0 && index < len) ? { key: keys[index], value: target[keys[index]] } : null; }, getKey(index = _index) { this.indexFilter(); return (index >= 0 && index < len) ? keys[index] : null; }, getValue(index = _index) { this.indexFilter(); return (index >= 0 && index < len) ? target[keys[index]] : null; }, initIndex() { _index = 0; this.flushProp(); return this; }, getIndex() { return _index; }, delProp(keyIndex = _index) { // 删除Key及对应值 delete target[keys[keyIndex]]; this.flushProp(); return this; }, setProp(obj) { Object.assign(target, obj); this.flushProp(); return this; }, getObj() { return target; }, setLoop(open=false){ loop = open; }, flushProp() { keys = Object.keys(target); len = keys.length; if (_index >= len) { _index = len - 1; } if (_index <= 0) { _index = 0; } return this; }, indexFilter(){ if(_index<0){ _index =0; return; } if(_index>=len){ _index=len-1; } } } }
// 测试
let obj = { name: 'avenda', age: '245', ccc: 'ccc' } let oI = iteratorProxy(obj); oI.setProp({ newName: 'dog' }) // oI.setLoop(true); while(oI.hasNext()){ print('next',oI.next()) } while (oI.hasPre()) { print('pre',oI.pre()) } print(oI.getIndex())
6.------------------generator状态机------------------------
let draw = function (count) { print(`剩余${count}次`) } let residue = function* (count) { while (count>0) { count--; yield draw(count); } } let start = residue(5); let btn = document.createElement('button'); btn.id = 'start'; btn.textContent = "抽奖"; document.body.appendChild(btn); document.getElementById('start').addEventListener('click',function () { start.next(); },false)
7.------------------generator长轮询------------------------
let ajax = function* () { yield new Promise((resolve, reject)=>{ setTimeout(()=>{ resolve({code:0}) },200) }) } let pull = function () { let generator = ajax(); let step = generator.next(); step.value.then((d)=>{ if (d.code===0) { setTimeout(()=>{ console.log('wait') pull(); },1000); }else{ console.log(d); } }); } // pull()
8.---------------@decorator修饰器-------------------
let readonly = function (target, name, descriptor) { descriptor.writable = false; return descriptor; } class Test{ @readonly time(){ return '2017-03-11'; } } let test = new Test(); let addName = function (target, name, descr) { target.staticProps = 'hello'; } @addName class Test2 { } console.log(Test2.staticProps)
9.---------------class + call-------------------
class A{ constructor() { this.a = '我是A的a'; } } // noinspection JSAnnotator function doSth(args){ console.log(args); console.log(this.a) } let a = new A(); doSth.call(a,'我是个小白');
能敲代码, 时不时画画, 时而玩玩户外, 拍拍喜欢的景象, 人生, 就够了...