Object.create() 创建实例时原型链如何追踪
使用 object.create() 创建实例时,可以通过 console.dir() 查看实例的 [[prototype]] 属性来追踪原型链。该方法允许你直接指定原型对象,从而清晰地看到继承关系。

在调试过程中,你可以在浏览器控制台中输入以下代码来观察原型链:
function Parent() {
this.name = 'Parent';
}
Parent.prototype.sayHello = function() {
console.log('Hello from Parent');
};
function Child() {
this.name = 'Child';
}
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
const childInstance = new Child();
console.dir(childInstance); // 查看原型链
通过 console.dir(),你可以看到一个树状结构,展示了 childInstance 的原型链:childInstance -> Child.prototype -> Parent.prototype -> Object.prototype。
instanceof 运算符如何验证继承关系
instanceof 运算符用于检查一个对象是否是某个构造函数的实例,它通过遍历原型链来验证继承关系。如果对象的原型链中包含该构造函数的 prototype 属性,则返回 true。

在调试过程中,你可以使用 instanceof 来验证继承关系:
console.log(childInstance instanceof Child); // true console.log(childInstance instanceof Parent); // true console.log(childInstance instanceof Object); // true
这些输出表明 childInstance 是 Child、Parent 和 Object 的实例,因为它沿着原型链找到了这些构造函数。
当原型链中出现循环引用时会发生什么
当原型链中出现循环引用时,JavaScript 引擎会抛出 RangeError: Maximum call stack size exceeded 错误。这是因为在遍历原型链时,引擎会无限递归,导致调用栈溢出。
为了避免这种情况,确保原型链中没有循环引用。例如,如果你不小心将 Parent.prototype 设置为 Child.prototype,就会形成循环引用:
Child.prototype = Parent.prototype; // 错误:可能导致循环引用 Parent.prototype = Child.prototype; // 错误:可能导致循环引用
正确的做法是使用 Object.create() 来创建新的原型对象,而不是直接赋值:
Child.prototype = Object.create(Parent.prototype); // 正确:避免循环引用
这样,Child.prototype 是一个新的对象,其原型是 Parent.prototype,从而避免了循环引用。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











