javascript继承的规范化写法是组合寄生式继承,它通过parent.call(this)继承实例属性、object.create(parent.prototype)建立原型链、手动修复constructor,确保属性独立、原型正确、方法可调用、instanceof准确。

必须满足的四个关键点
任何规范化的继承实现,都要确保:
- 子类实例拥有独立的父类实例属性(比如 this.name、this.colors)
- 子类原型链正确指向父类原型(Child.prototype.__proto__ === Parent.prototype)
- 子类能直接调用父类原型上的方法(不重复创建,也不污染父类)
- instanceof 和 isPrototypeOf 判断结果准确
标准模板代码(ES5 兼容,无副作用)
这是目前主流规范(如 Airbnb、StandardJS)推荐的最小可靠写法:
function Parent(name) {
this.name = name;
this.colors = ['red', 'blue'];
}
Parent.prototype.sayName = function() {
return this.name;
};
function Child(name, age) {
Parent.call(this, name); // ✅ 继承实例属性
this.age = age;
}
Child.prototype = Object.create(Parent.prototype); // ✅ 建立原型链,不执行父构造函数
Child.prototype.constructor = Child; // ✅ 修复 constructor 指向
Child.prototype.sayAge = function() {
return this.age;
};
为什么 Object.create(Parent.prototype) 不可替代?
常见错误写法:Child.prototype = new Parent() 或 Child.prototype = Parent.prototype,都有严重问题:
- new Parent() 会真正执行父构造函数,可能初始化意外状态(比如发请求、改全局变量、push 到共享数组)
- Parent.prototype 直接赋值,会导致子类往原型上加方法时,意外修改父类原型
- Object.create 只建立 [[Prototype]] 链接,零副作用、轻量、语义精准
ES6 class 是语法糖,但行为完全对齐
下面这段代码和上面模板等价:
class Parent {
constructor(name) {
this.name = name;
this.colors = ['red', 'blue'];
}
sayName() { return this.name; }
}
class Child extends Parent {
constructor(name, age) {
super(name); // 等价于 Parent.call(this, name)
this.age = age;
}
sayAge() { return this.age; }
}
区别只在写法:class 强制要求 super() 调用,自动处理原型链与 constructor 修复,底层仍是 Object.create + call 模式。
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南











