javascript继承

来源:互联网 发布:数据统计与分析专业 编辑:程序博客网 时间:2024/05/22 15:12

原型继承
这里写图片描述

 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
原创粉丝点击