前端那些事

vuePress-theme-reco chenpeng    2020 - 2021
前端那些事 前端那些事

Choose mode

  • dark
  • auto
  • light
首页
文章目录
  • Browser
  • CSS
  • ES6
  • JavaScript
  • Network
  • TypeScript
  • Vue
  • Vue3
  • Webpack
标签
时间轴
GitHub
author-avatar

chenpeng

85

Article

25

Tag

首页
文章目录
  • Browser
  • CSS
  • ES6
  • JavaScript
  • Network
  • TypeScript
  • Vue
  • Vue3
  • Webpack
标签
时间轴
GitHub
  • ES6-API

    • Proxy
    • Reflect

Reflect

vuePress-theme-reco chenpeng    2020 - 2021

Reflect

chenpeng 2020-11-30 ES6 API

# 1.概念

Reflect 是 ES6 为了操作对象而新增的 API,它是一个全局的对象,原型是 Object(Reflect 的 API 与 Proxy 的相同)

# 2.作用

  1. 将 Object 对象的一些明显属于语言内部的方法(比如 Object.defineProperty),放到 Reflect 对象上,以后就可以从 Reflect 对象上拿到语言内部的方法
  2. 在使用对象的 Object.defineProperty(obj, name, {}) 时,如果出现异常的话,会抛出一个错误,需要使用 try... catch 去捕获,但是使用 Reflect.defineProperty(obj, name, desc) 则会返回 false
try {
  Object.defineProperty(target, property, attributes);
} catch(e) {
  // 失败
}

// 新写法
if (Reflect.defineProperty(target, property, attributes)) {
  // success
} else {
  // failure
}
1
2
3
4
5
6
7
8
9
10
11
12

# 3.Reflect 方法

get() 方法用于获取对象的属性值,接受参数如下:

  1. target:目标对象
  2. key:被获取的属性名
  3. receiver:上下文 this 对象
const person = {
    name: 'zhangsan'
};
console.log(Reflect.get(person, 'name')); // zhangsan
1
2
3
4

set() 方法用于设置对象的属性值,接受参数如下:

  1. target:目标对象
  2. key:被获取的属性名
  3. value:新属性值
  4. receiver:上下文 this 对象

该方法返回一个布尔值,表示属性是否设置成功

const person = {
    name: 'zhangsan'
};
const result = Reflect.set(person, 'name' ,'zhaosi');
console.log(person); // zhaosi
console.log(result); // true
1
2
3
4
5
6