【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 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

科学熊

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值