Object.getPrototypeOf()用于获取对象直接原型,返回其[[Prototype]]指向的对象或null;等价于__proto__但更标准安全;不接受原始值,否则抛TypeError。

Object.getPrototypeOf() 是 JavaScript 中获取对象**直接原型(即内部 [[Prototype]])**的标准方法,返回该对象的原型对象(也就是它的 __proto__ 指向的那个对象),如果对象没有原型(比如 Object.create(null) 创建的对象),则返回 null。
基本用法:获取普通对象的原型
几乎所有对象都有原型,默认继承自 Object.prototype:
const obj = { a: 1 };
console.log(Object.getPrototypeOf(obj) === Object.prototype); // true
console.log(Object.getPrototypeOf(obj)); // { constructor: ƒ, __defineGetter__: ƒ, ... }
注意:Object.getPrototypeOf(obj) 等价于 obj.__proto__,但推荐使用前者,因为 __proto__ 是非标准、已废弃的访问器属性,仅用于兼容,而 Object.getPrototypeOf() 是 ECMAScript 标准方法,更可靠、更安全。
获取构造函数实例的原型链起点
对于通过构造函数或 class 创建的实例,它返回的是该构造函数的 prototype 对象:
function Person(name) {
this.name = name;
}
const p = new Person('Alice');
console.log(Object.getPrototypeOf(p) === Person.prototype); // true
// 类同理
class Animal {}
const dog = new Animal();
console.log(Object.getPrototypeOf(dog) === Animal.prototype); // true
处理 null 原型和内置对象
某些对象被显式设置为无原型,此时返回 null:
const noProto = Object.create(null); console.log(Object.getPrototypeOf(noProto)); // null // 数组、日期等内置对象也适用 console.log(Object.getPrototypeOf([1, 2]) === Array.prototype); // true console.log(Object.getPrototypeOf(new Date()) === Date.prototype); // true
⚠️ 注意:Object.getPrototypeOf(null) 或 Object.getPrototypeOf(undefined) 会抛出 TypeError —— 它只接受**对象类型**参数。传入原始值(如字符串、数字、null、undefined)会报错。
与原型链遍历配合使用
结合 Object.getPrototypeOf() 和循环,可手动遍历整个原型链(直到 null):
function getPrototypeChain(obj) {
const chain = [];
let current = obj;
while (current !== null) {
chain.push(current);
current = Object.getPrototypeOf(current);
}
return chain;
}
console.log(getPrototypeChain({}));
// [ {}, Object.prototype, null ]
这比依赖 __proto__ 更健壮,也便于调试原型继承关系。


















