js---继承

原型链(传统)

过多的继承了没用的属性

Son-->Father-->Grand

Grand.prototype.lastName="Ji";
function Grand(){
    
}

var grand=new Grand();

Father.prototype=grand;
function Father(){
    this.name="hehe";
}

var father=new Father();

Son.prototype=father;
function Son(){
    
}

var son=new Son();

借用构造函数

借用构造函数的原型对象实现继承

实现方法的借用

  • 不能继承借用构造函数的原型
  • 代码累赘,每次调用其构造器都会开辟新的空间来存放这个方法
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);  //借用Person构造器
    this.grade=grade;
}

var student=new Student();

共有原型

         Father.prototype

Father                        Son
Father.prototype.lastName="Deng";
function Father(){
    
}

function Son(){
    
}

Son.prototype=Father.prototype; //son和fanther继承自同一个原型

封装:

function inherit(Target,Origin){
    Target.prototype=Origin.prototype;
}
// 一定要先继承后用,否则new出的son对象的原型就不是指向Father.prototype,得重写原型。
inherite(Son,Father);

var son=new Son();

缺点:不能实现在不影响其他函数的前提下为某个函数私自添加属性

son.prototype.sex="male";
console.log(son.sex); //male
console.log(father.sex); //male

圣杯模式

弥补共有原型的缺点

              Father.prototype
              
                          function F(){ }
                              F.prototype=Father.prototype;
                                   Son.prototype=new F();
                         
Father                          Son 
function inherit(Target,Origin){
    function F(){}
    F.prototype=Orign.prototype;
    Target.prototype=newF();
}

console.log(son.constructor); //function Father(){}

//Son._proto_-->new F()._proto_-->Father.prototype

希望son的constructor是Son
function inherit(Target,Origin){
    function F(){}
    F.prototype=Orign.prototype;
    Target.prototype=newF();
    Target.prototype.constructor=Target;
    Target.prototype.uber=Origin.prototype; // 希望我们构造出的对象son能够找到自己的超类(超级父级,究竟继承自谁)【超类:super(关键字)改名】
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值