ES6 study notes 4 end --- Reflect, Proxy, Generator, Iterator

ES6(2015)

Reflection Reflect

Call the method .apply ()

// ES5
Math.floor.apply(null,[3.7])  // 3

// ES6
Reflect.apply(Math.floor,null,[3.7]) 

Role: the method can be used as parameters, according to the actual situation change the method name

// ES5 
let price = 91.5
if(price > 100){
	price = Math.floor.apply(null,[price])
}else {
	price = Math.ceil.apply(null,[price])
}
// ES6
Reflect.apply(price >100 ? Math.floor : Math.ceil,null,[price])

Instantiate the class .construct ()

Examples of objects .construct ()

// ES5
let d = new Date()
// ES6
let d = Reflect.construct(Date,[])  // 无参使用 空数组

The method of instance objects .defineProperty () & .deleteProperty ()

// 定义属性
const student = {}
const o = Object.defineProperty(student,'name',{value:'Mike'}) // {name: 'Mike'}
const r = Reflect.defineProperty(student,'name',{value:'Mike2'}) // true
// 删除属性
const obj = {x:1,y:2}
const o = Object.deleteProperty(obj,'x') // {y:2}
const r = Reflect.deleteProperty(obj,'x') // true
// 查看属性
const obj = {x:1,y:2}
const o = obj.x  // 1
const r = Reflect.get(obj,'x')  // 1
// 查看属性描述符
const r = Reflect.getOwnPropertyDescriptor(obj,'x') // writable
// 查看原型对象
const ge = Reflect.getPropertyOf(obj)
// 查看属性是否存在
const r = Reflect.has(obj,'x')  // Reflect 特有
// 可扩展
const r = Reflect.isExtensible(obj) 
// 冻结扩展性
const z = Object.freeze(obj)
const r = Relfect.preventExtensions(obj)
// 查看属性名
const r = Reflect.ownKeys(obj)
// set
Reflect.set(obj,'z',4)
// 修改原型对象
Reflect.setPrototypeOf(obj,String.prototype) // 将对象变成了 string

Proxy Proxy

Intermediary, to protect the original information, instead of Object.defineProperty ()

let o = {
    name : 'xm',
    price: 190
}
window.addEventListener('error',(e)=>{
    console.log(e.message)
    report('./') // 统一监控的方法
},true)

validator = function (target,key,value){
    if(Reflect.has(key)){
        if(key === 'price'){
            if(value >300){
                throw new TypeError('price exceed 300')
            }
        }
        target[key] = value
    }else {
        return false // 阻止写操作,只读
    }
}
let d = new Proxy(0,{
    get(target,key){
        if(key === 'price'){
            return target[key] + 20
        }else {
            return target[key] || ''
        }
    },
    set:validator
})
console.log(d.price) // 210 经过代理改变了

let r = Proxy.revocable(o,{ // 可撤销代理
    get(target,key){
        if(key === 'price'){
            return target[key] + 20
        }else {
            return target[key] || ''
        }
    }
})
let p = r.proxy.price // 相当于 d.price 
console.log(p) // 读取了数值
setTimeout(()=>{
    d.revoke() // 代理销毁
},1000)

effect:

  1. When the original information protection, access to information, the information can be adjusted
  2. Prevent modification of information
  3. A validator, when modification information, value range is exceeded block
  4. Information monitoring, trigger the check's

Generator Generator

Pause cycle

function * loop (){
	for (let i = 0 ; i < 3; i ++ ){
		yield console.log(i)
	}
}
const l = loop() // 此时一次值也没有
l.next() // 0
l.next() // 1
l.next() // 2
l.next() // 没了 
// 每次 遇到 yield 就停 
// 依靠next() 来执行每一次的循环

grammar

* Define the method, each encounter yield will stop waiting for instructions, until .next (val) execution, will skip a yield, and assign to yield, affect the value of yield equal sign on the left.

function * gen(){
    try {
        let val
        val = yield 1
        console.log(val)
    } catch (e){
        console.log(e.message)
    }
}

const l = gen()
const n1 = l.next() // 1  n1: {undefined,false}
const t1 = l.throw(new Error('ss')) // 使yield 异常
const r1 = l.return() // 提前结束
const n2 = l.next() // undefined  n2: {undefined,true}

Iterator Iterator

Can not traverse the object

let a = {
    b :{
        c: [1,2,3,4,5],
        d: [11,22,33,44,55,66],
        e: [111,222,333,444]
    },
    kk:{},
    zz:{}
}
// 将 c,d,e 中的数组 统一成一个数组 
// 常规做法 耦合度不够
let r = []
for(let [k,v] of Object.entries(a.b)){
    r = r.concat(v)
}
console.log(r) // 变成了新的数组

Fixed format to the subject increases walker

// 理想做法
let r = []
for (let v of a ){
    r.push(v)
}
// 于是 , 需要增加遍历器接口
// 入口this固定格式 可迭代协议
a[Symbal.iterator] = function(){
    // 逻辑
    let a = this.a
    let keys = Reflect.ownKeys(a)
    let values = []
    // 出口固定格式 迭代器协议
    return {
        next(){
            if(!value.length){
                if(keys.length){
                   values = a[keys][0]   
                   keys.shift()
                }
            }
            done:!value.length,
            value:values.shift()
        }
    }
}

Generator is used to traverse to the subject increases

// 上步可见,迭代器协议的格式 和 Generator 的 返回值格式 完全一样.其实,Generator 就是一个迭代器协议.
a[Symbol.iterator] = function * (){
    let a = this.a
    let keys = Reflet.ownKeys(a)
    let values = []
    while(1){
        if(!values.length){
            if(keys.length){
                values = a[keys[0]]
                keys.shift()
                yield valuse.shift()
            }else {
                return false
            }
        }else {
            yield values.shift()
        }
    }
}

Guess you like

Origin www.cnblogs.com/sirenvoid/p/12655919.html