一、原型链的继承
实现
function Parent(){
this.name = "ParentName";
this.actions = ['sing','jump','rap']
}
Parent.prototype.sas = "22"
function Child(){}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
const c1 = new Child();
console.log(Child.prototype.__proto__)
缺点
1.父类存在引用类型,其中一个实如果改变了此变量,那么所有实例都会共享
2.无法传参给Parent
二、构造函数继承
实现
function Parent(name){
this.name = name;
this.actions = ['sing','jump','rap'];
}
function Child(name){
Parent.call(this,name);
}
const c1 = new Child("c1");
const c2 = new Child("c2");
c1.actions.push("basketball");
console.log(c1);
console.log(c2);
缺点
1.浪费内存(每new一个对象就会在父类this很多属性和方法)
三、组合继承
实现
function Parent(name,actions){
this.name = name;
this.actions = actions;
}
Parent.prototype.getName = function(){
console.log(this.name,"调用了getName");
}
function Child(){
Parent.apply(this,arguments);
}
Child.prototype = new Parent();
Child.prototype.constructor = Child;
const c1 = new Child("c1",["eat","run"]);
c1.actions.push("gogo");
const c2 = new Child("c2",["sleep"]);
console.log(c1);
console.log(c2);
console.log(c1.getName === c2.getName);
c1.getName();
c2.getName();
缺点
1.调用了两次构造函数,生成了多余的属性,浪费不必要的内存(比构造函数少)
四、寄生组合式继承
实现
function Parent(name,actions){
this.name = name;
this.actions = actions;
}
Parent.prototype.getName = function(){
console.log(this.name,"调用了getName");
}
function Child(){
Parent.apply(this,arguments);
}
let TempFnction = function(){};
TempFnction.prototype = Parent.prototype;
Child.prototype = new TempFnction();
Child.prototype.constructor = Child;
const c1 = new Child("c1",["eat","run"]);
c1.actions.push("gogo");
const c2 = new Child("c2",["sleep"]);
Child.prototype.ap = function(){
}
console.log(Child.prototype);
console.log(Parent.prototype);
console.log(c1);
console.log(c2);
console.log(c1.getName === c2.getName);
c1.getName();
c2.getName();
五.Class实现继承
实现
class People {
constructor(name) {
this.name = name;
this.actions = ["sing"]
}
eat() {
console.log(`${this.name} eat something`)
}
}
class Teacher extends People {
constructor(name,major) {
super(name)
this.major = major
}
teach() {
console.log(`${this.name} 教授 ${this.major}`)
}
}
const zhangsan = new Teacher('张三',"化学")
const wanglaoshi = new Teacher('王老师', '语文')
zhangsan.eat();
wanglaoshi.eat();
zhangsan.actions.push("jump");
console.log(zhangsan);
console.log(wanglaoshi)
wanglaoshi.teach();
zhangsan.teach();
console.log(zhangsan.teach === wanglaoshi.teach);