美文网首页
Reflect的玩法(用来操作一个对象)

Reflect的玩法(用来操作一个对象)

作者: tenro | 来源:发表于2021-07-01 18:03 被阅读0次

    Reflect.get(target, propertyKey, receiver)

    var myObj = {
        foo: 1,
        bar: 2,
        get baz(){
            return this.foo + this.bar
        }
    }
    let a = Reflect.get(myObj,'foo');
    let b = Reflect.get(myObj,'bar');
    let c = Reflect.get(myObj,'baz');
    let d = Reflect.get(myObj,'name')
    
    console.log(a,b,c,d) //1,2,3,undefined
    

    Reflect.get中的第三个参数:

    var person={
        name:"Alice",
        age: 18,
        get say(){
            console.log(this.name + "今年" + this.age)
        },
        see(){
            console.log(this.name + " 没看见该方法声明的'get' !")
        }
    }
    
    let receiverObj = {
        name: "Tom",
        age: "27"
    }
    
    Reflect.get(person, 'say', receiverObj) //会直接执行了这个方法并输出的内容:Tom今年27
    Reflect.get(person, 'see', receiverObj)  // 返回定义的方法 ƒ see(){  console.log(this.name) }
    

    Reflect.set(target, propertyKey, value, receiver)
    ⚠️注意:可以通过目标对象的方法去改变另一个对象的值, 功能联想下apply, call, bind

    var myObj = {
        foo: 1,
        set bar(value){
            return this.foo = value;
        }
    }
    
    let receiverObj = {
        foo: 4
    }
    
    Reflect.set(myObj, 'foo', 2, receiverObj);
    console.log(myObj.foo) //1
    console.log(receiverObj.foo) //2
    

    Reflect.has
    ⚠️:判断目标对象是否存在某个属性

    let person = {
        name: 'Alice',
        age: 18
    }
    
    let property = 'name'
    console.log(Reflect.has(person,property))//true
    console.log(Reflect.has(person,'hobby')) //false
    

    Reflect.ownKeys
    ⚠️:用来返回所有的对象里的所有属性名称

    let person = {
        name: 'Alice',
        age: 18
    }
    
    console.log(Reflect.ownKeys(person)) //Array(2) ["name", "age"]

    相关文章

      网友评论

          本文标题:Reflect的玩法(用来操作一个对象)

          本文链接:https://www.haomeiwen.com/subject/mbwjultx.html