reflect.get 是 es6 提供的元编程方法,用于安全、可控地读取对象属性,语法为 reflect.get(target, propertykey, receiver),支持代理拦截、getter this 绑定控制及嵌套属性安全访问。

Reflect.get 是 ES6 提供的元编程方法,用于安全、可控地读取对象属性,比直接使用点号或方括号更灵活,尤其适合代理(Proxy)、属性拦截、默认值处理等场景。
基础用法:替代 obj[prop] 的标准方式
最简单的用途是读取对象属性,语法为 Reflect.get(target, propertyKey, receiver):
- target:要读取的目标对象
- propertyKey:属性名(字符串或 Symbol)
- receiver(可选):指定 this 绑定对象,影响 getter 中的 this 指向
例如:
const obj = { a: 1, get b() { return this.a * 2; } };console.log(Reflect.get(obj, 'a')); // 1
console.log(Reflect.get(obj, 'b')); // 2
配合 Proxy 实现属性访问拦截
在 Proxy 的 get 拦截器中,推荐用 Reflect.get 转发原始操作,保证默认行为不丢失:
get(target, prop, receiver) {
if (prop in target) {
console.log(`读取属性: ${prop}`);
}
return Reflect.get(target, prop, receiver); // 正确转发
}
};
const proxy = new Proxy({ x: 42 }, handler);
proxy.x; // 输出"读取属性: x",返回 42
不用 Reflect.get 而写 target[prop] 可能破坏原型链或 this 绑定,尤其当属性是 getter 时。
处理继承与 getter 的 this 上下文
当目标对象有 getter 且依赖 this,receiver 参数就很重要:
const child = { __proto__: parent, get double() { return this.value * 2; } };
console.log(Reflect.get(child, 'double')); // 200(this 指向 child)
console.log(Reflect.get(child, 'double', parent)); // 200?不对 —— 实际是 200,但若 parent 也有 value,receiver 决定 this
关键点:receiver 是 getter 中的 this。若省略,默认为 target;显式传入可模拟不同调用上下文,常用于实现属性委托或 mixin。
安全读取嵌套属性(避免报错)
结合可选链(?.)或 try/catch 不如用 Reflect.get + 空值判断更主动:
return path.split('.').reduce((cur, key) => {
return cur && typeof cur === 'object' ? Reflect.get(cur, key) : undefined;
}, obj);
}
safeGet({ user: { name: 'Alice' } }, 'user.name'); // 'Alice'
safeGet({ user: null }, 'user.name'); // undefined
相比 obj?.user?.name,这种方式更易扩展(比如加日志、默认值、类型校验)。










