返回

ES6 的 Reflect 对象:比原生的反射 API 更强大

前端

Object.getPrototypeOf()Reflect.getPrototypeOf()

// 老写法:
const person = { name: 'John Doe' };
const prototype = Object.getPrototypeOf(person);
console.log(prototype); // Person { name: 'Person' }

// 新写法:
const prototype = Reflect.getPrototypeOf(person);
console.log(prototype); // Person { name: 'Person' }

Object.getOwnPropertyDescriptor()Reflect.getOwnPropertyDescriptor()

// 老写法:
const person = { name: 'John Doe' };
const descriptor = Object.getOwnPropertyDescriptor(person, 'name');
console.log(descriptor); // { value: 'John Doe', writable: true, enumerable: true, configurable: true }

// 新写法:
const descriptor = Reflect.getOwnPropertyDescriptor(person, 'name');
console.log(descriptor); // { value: 'John Doe', writable: true, enumerable: true, configurable: true }

Object.defineProperty()Reflect.defineProperty()

// 老写法:
const person = {};
Object.defineProperty(person, 'name', { value: 'John Doe' });
console.log(person.name); // 'John Doe'

// 新写法:
const person = {};
Reflect.defineProperty(person, 'name', { value: 'John Doe' });
console.log(person.name); // 'John Doe'

Object.deleteProperty()Reflect.deleteProperty()

// 老写法:
const person = { name: 'John Doe' };
delete person.name;
console.log(person.name); // undefined

// 新写法:
const person = { name: 'John Doe' };
Reflect.deleteProperty(person, 'name');
console.log(person.name); // undefined

Object.apply()Reflect.apply()

// 老写法:
const person = {
  name: 'John Doe',
  greet: function() {
    console.log(`Hello, my name is ${this.name}.`);
  }
};

const name = 'Jane Doe';

// 直接调用
person.greet(); // Hello, my name is John Doe.

// 使用 `apply()` 方法调用
Object.apply(person.greet, [person]); // Hello, my name is John Doe.

// 新写法:
const person = {
  name: 'John Doe',
  greet: function() {
    console.log(`Hello, my name is ${this.name}.`);
  }
};

const name = 'Jane Doe';

// 直接调用
person.greet(); // Hello, my name is John Doe.

// 使用 `Reflect.apply()` 方法调用
Reflect.apply(person.greet, person, [name]); // Hello, my name is Jane Doe.

Object.construct()Reflect.construct()

// 老写法:
const Person = function(name) {
  this.name = name;
};

const person = new Person('John Doe');

// 新写法:
const Person = function(name) {
  this.name = name;
};

const person = Reflect.construct(Person, ['John Doe']);

结论

Reflect 对象提供了比原生反射 API 更强大的功能,它可以用于实现各种常见的任务,例如:元编程、代理和拦截。通过使用 Reflect 对象,我们可以编写出更加灵活和强大的 JavaScript 代码。