Reflect对象的方法清单如下,共13个。
- Reflect.apply(target,thisArg,args)
- Reflect.construct(target,args)
- Reflect.get(target,name,receiver)
- Reflect.set(target,name,value,receiver)
- Reflect.defineProperty(target,name,desc)
- Reflect.deleteProperty(target,name)
- Reflect.has(target,name)
- Reflect.ownKeys(target)
- Reflect.isExtensible(target)
- Reflect.preventExtensions(target)
- Reflect.getOwnPropertyDescriptor(target, name)
- Reflect.getPrototypeOf(target)
- Reflect.setPrototypeOf(target, prototype)
上面这些方法的作用,大部分与Object对象的同名方法的作用都是相同的,而且它与Proxy对象的方法是一一对应的。
let obj = {
construct() {
console.log('sss');
},
name: 'aaa',
age: 12
}
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
const args = ['John', 30];
function add(a, b) {
return a + b;
}
//查找并返回`target`对象的`name`属性,如果没有该属性,则返回`undefined`。
//如果`name`属性部署了读取函数,则读取函数的`this`绑定`receiver`
let res1 = Reflect.get(obj, 'name')
console.log(res1);
console.log(obj);
//设置`target`对象的`name`属性等于`value`。如果`name`属性设置了赋值函数,则赋值函数的`this`绑定`receiver`。
let res2 = Reflect.set(obj, 'name', 'bbb')
console.log(res2);
console.log(obj);
//等同于`name in obj`
let res3 = Reflect.has(obj, 'name')
console.log(res3);
console.log(obj);
//等同于`delete obj[name]`。
let res4 = Reflect.deleteProperty(obj, 'name')
console.log(res4);
console.log(obj);
//等同于`new target(...args)`,这提供了一种不使用`new`,来调用构造函数的方法。
let res5 = Reflect.construct(Person, args)
console.log(res5);
console.log(obj);
//读取对象的`__proto__`属性,对应`Object.getPrototypeOf(obj)`。
let res6 = Reflect.getPrototypeOf(obj)
console.log(res6);
console.log(obj);
//设置对象的`__proto__`属性,对应`Object.setPrototypeOf(obj, newProto)`。
let res7 = Reflect.setPrototypeOf(obj, {
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
},
})
console.log(res7);
console.log(obj);
//等同于`Function.prototype.apply.call(fun,thisArg,args)`。一般来说,如果要绑定一个函数的this对象,可以这样写`fn.apply(obj, args)`,但是如果函数定义了自己的`apply`方法,就只能写成`Function.prototype.apply.call(fn, obj, args)`,采用Reflect对象可以简化这种操作。
//另外,需要注意的是,`Reflect.set()`、`Reflect.defineProperty()`、`Reflect.freeze()`、`Reflect.seal()`和`Reflect.preventExtensions()`返回一个布尔值,表示操作是否成功。它们对应的Object方法,失败时都会抛出错误。
const res8 = Reflect.apply(add, null, [5, 3]);
console.log(res8);
console.log(obj);