【ES6】JavaScript中Reflect

Reflect是JavaScript中的一个内建对象,它提供了一组方法,用于对对象和函数进行操作和检查。这些方法与内建对象的方法非常相似,但具有更高的灵活性。

以下是Reflect对象的一些常用方法:

1、Reflect.apply(target, thisArgument, argumentsList):调用目标函数,使用指定的参数列表。

function sum(a, b) {
  return a + b;
}
console.log(Reflect.apply(sum, null, [2, 3])); // 输出 5

2、Reflect.construct(target, argumentsList):使用指定的参数列表来调用目标函数,并创建一个新的实例。

class Rectangle {
  constructor(width, height) {
    this.width = width;
    this.height = height;
  }
  get area() {
    return this.width * this.height;
  }
}
const rect = Reflect.construct(Rectangle, [10, 20]);
console.log(rect.area); // 输出 200

3、Reflect.defineProperty(target, propertyKey, attributes):在目标对象上定义一个属性,并返回该属性的描述符。

const obj = {};
const desc = { value: 10, writable: true, enumerable: true };
Reflect.defineProperty(obj, 'prop', desc);
console.log(obj.prop); // 输出 10

4、Reflect.deleteProperty(target, propertyKey):删除目标对象上的属性。

const obj = { prop: 10 };
Reflect.deleteProperty(obj, 'prop');
console.log(obj.prop); // 输出 undefined

5、Reflect.get(target, propertyKey[, receiver]):从目标对象上获取指定属性的值,并返回给接收器。

const obj = { prop: 10 };
console.log(Reflect.get(obj, 'prop')); // 输出 10

6、Reflect.set(target, propertyKey, value[, receiver]):将指定属性的值设置为给定的值,并返回目标对象。

const obj = {};
Reflect.set(obj, 'prop', 10);
console.log(obj.prop); // 输出 10

7、Reflect.has(target, propertyKey):检查目标对象是否具有指定的属性。

const obj = { prop: 10 };
console.log(Reflect.has(obj, 'prop')); // 输出 true

8、Reflect.getOwnPropertyDescriptor(target, propertyKey):获取目标对象上指定属性的描述符。

const obj = { prop: 10 };
const desc = Reflect.getOwnPropertyDescriptor(obj, 'prop');
console.log(desc); // 输出 { value: 10, writable: true, enumerable: true }

你可能感兴趣的:(前端,es6,前端)