Reflect.getPrototypeOf()是获取对象原型的标准方法,等价于Object.getPrototypeOf()但语义更清晰、与Proxy trap对齐,要求参数为对象,否则抛TypeError,返回null表示无原型。

Reflect.getPrototypeOf() 是 JavaScript 中用于获取对象原型对象的标准方法。
基本用法:直接获取原型
它等价于 Object.getPrototypeOf(obj),但属于 Reflect 命名空间下的统一操作接口,语义更清晰,且在 Proxy 中配合使用更自然。
- 语法:
Reflect.getPrototypeOf(target) -
target必须是对象,否则抛出TypeError - 返回
target的内部[[Prototype]](即__proto__指向的对象)
和 Object.getPrototypeOf 的区别
两者行为完全一致,但 Reflect.getPrototypeOf 更强调“操作”语义,适合与 Proxy 的 trap(如 getPrototypeOf)对齐。
- 都返回
null当对象没有原型(例如Object.create(null)) - 都拒绝非对象参数(
Reflect.getPrototypeOf(123)报错,而Object.getPrototypeOf(123)会隐式包装再取原型,返回Number.prototype)
常见使用示例
✅ 正确用法:
立即学习“Java免费学习笔记(深入)”;
const obj = {};
console.log(Reflect.getPrototypeOf(obj)); // Object.prototype
const arr = [];
console.log(Reflect.getPrototypeOf(arr)); // Array.prototype
const nullProto = Object.create(null);
console.log(Reflect.getPrototypeOf(nullProto)); // null
❌ 错误用法:
Reflect.getPrototypeOf(42); // TypeError
Reflect.getPrototypeOf("hello"); // TypeError
Reflect.getPrototypeOf(undefined); // TypeError
在 Proxy 中的配合使用
当你需要拦截原型读取时,Proxy 的 getPrototypeOf trap 会接收 Reflect.getPrototypeOf 的调用:
const proxy = new Proxy({}, {
getPrototypeOf() {
console.log("原型被读取了");
return Reflect.getPrototypeOf(arguments[0]);
}
});
Reflect.getPrototypeOf(proxy); // 输出日志,并返回 Object.prototype
不复杂但容易忽略:它只读取,不修改;要设置原型请用 Reflect.setPrototypeOf() 或 Object.setPrototypeOf()。


















