js实现继承的几种方式

对象冒充实现继承(call)

缺点:无法继承原型链上的方法

function User(name,age) {
this.name = name;
this.age = age
   this.run = function(){
       alert(this.name+'在运动')
  }
}
function Menber (name,age){
   //call继承属性
User.call(this,name,age)
}
new Menber('李良荣').run()

原型链实现继承

缺点:实例化 子类无法给父类传参

function User(name,age) {
this.name = name;
this.age = age
   this.run = function(){
       alert(this.name+'在运动')
  }
}
function Menber (){
   
}
Menber.prototype = new User()
new Menber('lisi').run() //undefined.run

组合继承

原型链加构造函数组合继承模式(call和构造函数实例实现继承)

缺点:调用了两次父类构造函数

function User(name,age) {
this.name = name;
this.age = age
   
}
User.prototype.run = function () {  
   alert(this.name)
}
function Menber (name,age){
   User.call(this,name,age)
}
Menber.prototype = new User()
new Menber('lisi').run()

寄生组合继承(圣杯继承)

优点: 只调用了一次Parent构造函数,并且因此避免了再Parent.prototype上面创建不必要的,多余的属性。

function User(name,age) {
this.name = name;
   this.age = age
}
User.prototype.run = function () {  
   alert(this.name)
}
function Menber (name,age){
   User.call(this,name,age)
}
function prototype(child,parent) {  
       function F() { }
       F.prototype = parent.prototype
       new F().constructor = child;
       child.prototype = new F()
}
prototype(Menber,User)
console.log(new Menber('lisi','12'));

 

posted @ 2020-04-19 21:07  良荣十贰  阅读(153)  评论(0)    收藏  举报