通过Parent.call(this)可使父构造函数的this指向子类新实例,从而正确初始化父类实例属性;它不继承原型方法,需额外设置原型链或使用ES6的super()和extends自动处理。

在 JavaScript 中,通过 Parent.call(this) 在子类构造函数中调用父类构造函数,是实现**借用构造函数(Constructor Borrowing)** 的核心方式,用于在子类实例上初始化父类定义的实例属性(即写在 this.xxx = ... 上的属性),而不是原型方法。
为什么需要 .call(this)?
因为构造函数中的代码通常依赖 this 指向当前正在创建的实例。如果直接调用 Parent(),this 会指向全局对象(非严格模式)或 undefined(严格模式),导致属性被错误挂载,甚至报错。用 Parent.call(this) 可以强制让父构造函数内部的 this 指向子类新创建的实例,从而把父类的实例属性“复制”到子实例上。
基本写法(ES5 构造函数继承)
假设父类和子类都使用 function 声明:
function Animal(name, age) {
this.name = name;
this.age = age;
this.type = 'animal';
}
<p>function Dog(name, age, breed) {
// ✅ 关键:用 call 把 Animal 的实例属性初始化到 this(即新 Dog 实例)上
Animal.call(this, name, age);
// ✅ 子类自己的属性
this.breed = breed;
}</p><p>const dog = new Dog('旺财', 3, '柴犬');
console.log(dog.name); // '旺财'
console.log(dog.breed); // '柴犬'
console.log(dog.type); // 'animal' → 来自 Animal.call()</p>注意:.call(this) 只处理实例属性,不处理原型方法
Animal.call(this) 不会自动让 Dog.prototype 继承 Animal.prototype 上的方法(比如 Animal.prototype.eat)。若需方法复用,还需额外设置原型链:
当用户要求为 Java 代码添加注释、修改注释、审查注释、整理注释格式,或要求按照代码注释规范处理 Java 文件时,使用本技能。本技能用于统一生成和维护 Java 类注释模板、按 Git 对比 release 判断版本号、补充每行代码上方中文块注释、调整注释空行规则,并保持 Java 文件 UTF-8 无 BOM 编码。典型触发场景包括:补充类注释、更新 @version、检查 @author 来源、整理行尾注释、把注释放到代码上一行、检查注释是否符合规范、构建前检查 Java 注释风格。
立即学习“Java免费学习笔记(深入)”;
- 用
Dog.prototype = Object.create(Animal.prototype)建立原型继承 - 补回
constructor指向:Dog.prototype.constructor = Dog - 否则
dog instanceof Animal为false,且无法访问Animal.prototype上的方法
ES6 class 中的等价写法:super()
在 class 语法中,super(...args) 就是 Parent.call(this, ...args) 的语法糖,且必须在 this 被访问前调用:
class Animal {
constructor(name, age) {
this.name = name;
this.age = age;
this.type = 'animal';
}
}
<p>class Dog extends Animal {
constructor(name, age, breed) {
super(name, age); // ✅ 等价于 Animal.call(this, name, age)
this.breed = breed;
}
}</p>注意:extends 已自动处理了原型链(Dog.prototype.__proto__ === Animal.prototype),所以无需手动设 Object.create。

















