javascript继承

原型继承
这里写图片描述

 function Box(){
      this.name = 'Lee';
  }
  Box.prototype.name='Jack';//构造中有就从构造中取,没有就找原型

  function Desk(){
      this.age=12;
  }
  Desk.prototype = new Box();
  var desk = new Desk();
  alert(desk.name);//Lee

借用构造函数继承(对象冒充)

function Box(name,age){
      this.name = name;
      this.age = age;
      this.family = ['哥哥','姐姐','弟弟'];//引用类型放在构造中不会被共享
  }
  Box.prototype.run = function(){
    return this.name+this.age;
  }

  function Desk(name,age){
      Box.call(this,name,age);
  }

  var desk = new Desk();
  alert(desk.family);//哥哥,姐姐,弟弟
  alert(desk.run());//undefine这种方式继承不到原型

对象冒充+原型链继承

function Box(name,age){
      this.name = name;
      this.age = age;
      this.family = ['哥哥','姐姐','弟弟'];
  }

  Box.prototype.run = function(){
      return this.name+this.age;
  }

  function Desk(name,age){
      Box.call(this,name,age);
  }

  Desk.prototype = new Box();

  var desk = new Desk("Lee",12);
  alert(desk.family);//哥哥,姐姐,弟弟
  alert(desk.run())//Lee12

原型式继承

 function obj(o){       //o表示要传递进去的一个对象
      function F(){};   //F构造是一个临时新建的对象,用来存储传递过来的o对象
      F.prototype = o;  //将o赋值给F构造的原型对象
      return new F();
  }

  var box = {
      name:'Lee',
      age:12,
      family:['哥哥','姐姐','妹妹']
  };

  var box1 = obj(box);

  alert(box1.name);//Lee

最终版:寄生组合继承

//中转函数
  function obj(o){      //o表示要传递进去的一个对象
      function F(){};   //F构造是一个临时新建的对象,用来存储传递过来的o对象
      F.prototype = o;  //将o赋值给F构造的原型对象
      return new F();
  }

    //寄生函数
    function create(box,desk){
        var f = obj(box.prototype);//传入Box的原型对象
        //f.constructor = desk;     //原型对象的构造指向Desk
        desk.prototype = f;         //Desk的原型指向Box的原型
    }

    function Box(name,age){
        this.name = name;
        this.age = age;
    }

    Box.prototype.run = function(){
        return this.name + this.age +'运行中';
    }

    function Desk(name,age){
        Box.call(this,name,age);
    }

    create(Box,Desk);

    var desk = new Desk('Lee',12);
    alert(desk.run());//Lee12运行中
    alert(Desk.prototype.constructor);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值