原生js的8种类继承方式

1.原型链继承

Grand.prototype.lastName = "Yang";
function Grand(){
}
var grand = new Grand();
Father.prototype = grand;
function Father(){
}
var father = new Father();
Son.prototype = father;
function Son (){
}

缺点:
(1)过多地继承了没用的属性
(2)不支持多继承,子类只能继承自一个父类
(3)创建子类实例时,无法向父类构造函数传参

2.通过callapply借用构造函数

function Person(name,age,sex){
    this.name = name;
    this.age = age;
    this.sex = sex;
}
function Student(name,age,sex,grade){
    Person.call(this,name,age,sex);
    this.grade = grade;
}


缺点:
(1)不能借用构造函数的原型
(2)每次构造函数都要多走一个函数,增加了函数调用。

3.公有原型

Father.prototype.lastName = "Yang";
function Father(){
}
function Son(){
}
Son.prototype = Father.prototype;
var father = new Father();
var son = new Son();
  
  

缺点:
不能随便改动自己的原型,一个改了,另一个也会跟着改。

4.圣杯模式

var inherit = (function()
{
var F = function(){};
return function(Target,Origin){
    F.prototype = Origin.prototype;
    Target.prototype = new F();
    Target.prototype.constructor = Target;
    Target.prototype.uber = Origin.prototype;
}());
   
   

缺点:perfect
5.实例继承

function Father(){};
function Son(name){
    var instance = new Father();
    instance.name = name;
    return instance;
}
var son = new Son();
 
 

缺点:
(1)返回的实例是父类的,而不是子类本身的。
(2)不支持多继承。

6.拷贝继承

function Father(){};
function Son(name){
    var father = new Father();
    for(var prop in father){
        Son.prototype[prop] = father[prop];//最好用deepClone
    }
    this.name = name;
}
var son = new Son();
 
 

缺点:
(1)效率低,占内存
(2)无法获取父类不可枚举的方法

7.组合继承

function Father(name){};
function Son(){
    Father.call(this);
    this.name = name;
}
Son.prototype = new Father();
Son.prototype.constructor = Son;
var son = new Son();
 
 

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

8.寄生组合继承:
组合继承 + 圣杯模式

(本文转自)[https://blog.csdn.net/weixin_42897293/article/details/82318310]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值