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"]
网友评论