JavaScript 中原型链中类式继承怎么理解
类式继承的核心在于通过构造函数模拟类的行为,并利用原型链实现属性和方法的共享。具体做法是定义一个父类构造函数来初始化实例属性,再定义一个子类构造函数,在子类内部调用父类构造函数以继承实例属性,同时设置子类的原型为父类的实例以继承原型方法。

为什么需要手动调用父类构造函数
必须手动调用是因为原型链只能继承原型上的属性和方法,无法自动继承构造函数内部的实例属性。如果不手动调用,子类实例将丢失这些私有属性。

子类原型指向父类实例后如何正确识别类型
当子类原型被设置为父类实例时,`instanceof` 检查会沿着原型链向上查找,从而正确识别子类实例也是父类的实例。但此时 `constructor` 属性会指向父类构造函数,需要手动修正回子类构造函数以保持类型标识的准确性。
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name); // 继承实例属性
this.age = age;
}
Child.prototype = new Parent(); // 继承原型方法
Child.prototype.constructor = Child; // 修正 constructor
var child = new Child('Alice', 10);
child.sayName(); // 输出: Alice
console.log(child instanceof Child); // true
console.log(child instanceof Parent); // true
function Parent(name) {
this.name = name;
}
Parent.prototype.sayName = function() {
console.log(this.name);
};
function Child(name, age) {
Parent.call(this, name);
this.age = age;
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
var child = new Child('Bob', 5);
console.log(child.constructor === Child); // true
console.log(child.constructor === Parent); // false
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











