JavaScript中操作原型链报错本质是访问null或undefined的__proto__等属性;null是合法终点,undefined非对象不参与原型链;应使用Object.getPrototypeOf()配合判空安全遍历。

在 JavaScript 中操作原型链时遇到 undefined 或 null 报错,本质是因为试图访问它们的 __proto__、constructor 或 prototype 属性——而这两者没有原型(null 的原型是终点,undefined 不是对象,根本不可访问原型)。
明确原型链的终点:null 是合法终点,undefined 不参与链
Object.getPrototypeOf(obj) 或 obj.__proto__ 在到达 Object.prototype 后会返回 null,这是设计使然,不是错误。但如果你手动写 obj.__proto__.__proto__.__proto__ 这类链式访问,一旦某步结果是 null 或 undefined,再继续取 __proto__ 就会报 Cannot read property '__proto__' of null/undefined。
注意:undefined 本身不是对象,没有 __proto__;它通常出现在变量未赋值、属性不存在、函数无返回值等场景,不是原型链中的有效节点。
安全遍历原型链的推荐方式
用 Object.getPrototypeOf() 配合显式判空,避免直接链式点取:
立即学习“Java免费学习笔记(深入)”;
- 始终用
Object.getPrototypeOf(obj) !== null判断是否还能继续向上 - 不要依赖
obj.__proto__(非标准且在严格模式下可能受限) - 对不确定是否为对象的值,先用
obj != null && typeof obj === 'object'做前置校验
示例:
function getPrototypeChain(obj) {
const chain = [];
let current = obj;
while (current != null && typeof current === 'object') {
chain.push(current);
current = Object.getPrototypeOf(current);
}
return chain;
}
// ✅ 安全:传入 {}, null, undefined, 42 都不会报错
访问 constructor 或 prototype 时的常见陷阱
obj.constructor 可能是 undefined(比如 Object.create(null) 创建的对象),func.prototype 在非函数上访问会报错(如 42.prototype)。
- 读
constructor前,先确认对象有原型且原型上有该属性:Object.getPrototypeOf(obj)?.constructor(可选链) - 读
func.prototype前,用typeof func === 'function'校验 - 需要获取某个值的原型时,优先用
Object.getPrototypeOf(Object(value))统一转为对象再操作
工具函数封装:防崩的原型链操作
把容错逻辑收进小函数,复用更安心:
// 安全获取第 n 级原型(0 表示自身,1 表示 __proto__,以此类推)
function safeGetPrototypeOf(obj, depth = 1) {
if (depth < 0 || obj == null || typeof obj !== 'object') return undefined;
let current = obj;
for (let i = 0; i < depth; i++) {
current = Object.getPrototypeOf(current);
if (current === null) break;
}
return current;
}
// 安全读取 constructor(不抛错,找不到返回 undefined)
function safeGetConstructor(obj) {
const proto = Object.getPrototypeOf(obj);
return proto?.constructor;
}


















