javascript中用call实现属性继承的本质是在子构造函数内部借用父构造函数执行,让this指向新创建的子实例,从而把父类的实例属性“复制”到子实例上;它解决实例属性继承问题,但不继承原型方法。

JavaScript 中用 call 实现属性继承,本质是**在子构造函数内部借用父构造函数执行,让 this 指向新创建的子实例,从而把父类的实例属性“复制”到子实例上**。这不是真正的原型继承,而是构造函数继承(也叫对象冒充),主要解决的是**实例属性的继承问题**。
为什么需要 call 来继承属性?
直接调用父构造函数(如 Parent())会让 this 指向全局对象(非严格模式)或 undefined(严格模式),无法把属性挂到子实例上。而 call 可以显式绑定 this,确保父构造函数中的 this.xxx = xxx 赋值操作作用于当前子实例。
基本写法:在子构造函数中调用父构造函数
示例:
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
function Parent(name, age) {
this.name = name;
this.age = age;
}
function Child(name, age, grade) {
// 关键:用 call 把 Parent 的初始化逻辑“借”给当前 Child 实例
Parent.call(this, name, age); // this 指向 new Child() 创建的对象
this.grade = grade;
}
const child1 = new Child('小明', 10, '五年级');
console.log(child1.name); // '小明'
console.log(child1.age); // 10
console.log(child1.grade); // '五年级'
注意:call 只继承实例属性,不继承原型方法
call 只执行父构造函数体内的代码,所以只能拿到 this.xxx 定义的属性,无法自动获得父类原型上的方法(如 Parent.prototype.sayHi)。若需方法继承,必须额外设置原型链:
- 用
Child.prototype = Object.create(Parent.prototype)建立原型继承 - 修复
constructor指针:Child.prototype.constructor = Child
完整组合写法:
function Parent(name) {
this.name = name;
}
Parent.prototype.sayHi = function() {
return `Hi, I'm ${this.name}`;
};
function Child(name, age) {
Parent.call(this, name); // 继承实例属性
this.age = age;
}
// 同时继承原型方法
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
const c = new Child('小红', 9);
console.log(c.sayHi()); // 'Hi, I'm 小红'
常见误区提醒
-
不能只靠 call 实现完整继承:它不改变原型关系,子实例
instanceof Parent会返回false - 参数要手动传递:call 的第二个起是实际参数,需与父构造函数签名对齐,不能漏传或错序
-
ES6 class 中对应的是 super():class 内部的
super(name, age)底层机制类似Parent.call(this, ...),但更安全、强制调用
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










