| 继承方式 | 核心 | 关系 |
|---|
| 原型继承 | 把父类公有作为子类公有 | 继承公有属性 |
| 构造继承 | 把父类私有作为子类私有 | 继承私有属性 |
| 组合继承 | 把父类公有作为子类公有,把父类私有作为子类私有 | 原型继承+构造继承 |
| 寄生继承 | 构造一个代理,让代理的 prototype 指向父类的 prototype | 在原型继承的基础上进行增强 |
| ES6继承 | extends | 继承父类所有属性 |
原型继承
function Father(){
this.name = '笨鸟';
this.age = 24;
}
Father.prototype.get = function(){
console.log(this.name,this.age);
}
function Ann(){}
Ann.prototype = Father.prototype;
Child.prototype = new Ann();
Chile.prototype.constructor = Child;
function Child(){}
var obj = new Child();
console.log(obj);
构造继承
function Father( name, age){
this.name = name;
this.age = age;
}
Father.prototype.get = function(){
console.log(this.name, this.age);
}
function Child( name, age){
Father.call( this, name, age);
}
var obj = new Child('笨鸟',24);
console.log(obj);
组合继承
function Father(name,age){
this.name = name;
this.age = age;
}
Father.prototype.school = 'Good';
function Ann();
Ann.protoype = Father.prototype;
Child.prototype = new Ann();
Child.prototype.constructor = Child;
function Child(name,age){
Father.call(this,name,age);
}
var obj = new Child('笨鸟',24);
console.log(obj);
寄生继承
function Father(){
this.name = '笨鸟';
this.age = 24;
}
Father.prototype.get = function(){
console.log(this.name,this.age);
}
function Ann();
Ann.protoype = Father.prototype;
function Child(){}
Child.prototype = new Ann();
Child.prototype.constructor = Child;
Ann.prototype.school = 'Good';
var obj = new Child();
console.log(obj);
ES6继承
class Father {
constructor(name, age) {
this.name = name;
this.age = age;
}
get() {
console.log("个人信息:" + this.name + this.age);
}
}
class Child extends Father {
constructor(name, age) {
super(name, age);
}
}
let obj = new Child('笨鸟',25);
console.log(obj);