javascript通过原型链与构造函数手动模拟类继承:1.用object.create(parent.prototype)继承原型并修复constructor;2.在子类构造函数中用parent.call(this, ...)调用父构造;3.es6 class中super()即等价实现。

JavaScript 中没有传统面向对象语言里的“类继承链式构造调用”语法,但可以通过原型链 + 构造函数手动模拟出类似效果:子类构造函数中调用父类构造函数,并确保 this 正确绑定,同时让子类实例能访问父类原型上的方法。关键在于三步:继承原型、调用父构造、修正 constructor。
1. 原型继承:让子类原型指向父类实例(或干净的父类原型副本)
直接赋值 Child.prototype = Parent.prototype 会污染父类原型,应使用 Object.create(Parent.prototype) 创建新对象作为子类原型,既继承方法,又不共享属性。
示例:
function Parent(name) { this.name = name; }
Parent.prototype.sayHello = function() { console.log('Hello, ' + this.name); };
function Child(name, age) { this.age = age; }
Child.prototype = Object.create(Parent.prototype); // 关键:建立原型链
Child.prototype.constructor = Child; // 修复 constructor 指向
2. 构造调用:在子类构造函数中显式调用父类构造函数
仅靠原型继承不会自动执行父类初始化逻辑(如给 this 赋值),必须在 Child 内部用 Parent.call(this, name) 手动触发,保证父类代码在子类 this 上运行。
在 Java 中初始化和管理阿里云 SDK客户端。包括单例模式、线程安全、endpoint 与 region 配置、VPC 终端节点、同步与异步等。
常见写法:
- 用
Parent.call(this, ...args)绑定this并传参(最常用) - ES6+ 可用
super(...args)(仅限 class 语法,底层仍等价于 call) - 避免
new Parent()—— 会创建多余对象且无法控制this
3. 完整可运行示例(ES5 风格)
把上面两步组合起来,就能实现真正的“链式构造”:
function Animal(name) { this.name = name; }
Animal.prototype.eat = function() { console.log(this.name + ' is eating'); };
function Dog(name, breed) {
Animal.call(this, name); // ✅ 关键:链式调用父构造
this.breed = breed;
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
Dog.prototype.bark = function() { console.log('Woof!'); };
const dog = new Dog('Leo', 'Golden Retriever');
dog.eat(); // Leo is eating → 来自 Animal 原型
dog.bark(); // Woof! → 来自 Dog 原型
console.log(dog instanceof Dog); // true
console.log(dog instanceof Animal); // true
4. ES6 class 的等效写法(更简洁,本质相同)
class 语法是语法糖,super() 就是自动帮你做了 Animal.call(this, ...) 和原型设置:
class Animal {
constructor(name) { this.name = name; }
eat() { console.log(this.name + ' is eating'); }
}
class Dog extends Animal {
constructor(name, breed) {
super(name); // ✅ 等价于 Animal.call(this, name)
this.breed = breed;
}
bark() { console.log('Woof!'); }
}
注意:super() 必须在 this 使用前调用,否则报错 —— 这正是引擎强制保障“链式构造”的机制。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










