js 构造函数、原型继承

//定义所有飞行物的父类型的构造函数
function Flyer(fname,fspeed){
  this.fname=fname;
  this.fspeed=fspeed;
}
Flyer.prototype.fly=function(){ //fly放在Flyer.prototype
  console.log(this.fname+"以"+this.fspeed+"速度飞行");
}

1、构造继承

//定义第一种飞行物: Bee,继承并扩展父类型Flyer

//定义独有的构造函数,继承并扩展Flyer构造函数----apply继承/call继承
function Bee(fname,fspeed,award){

  console.log(arguments); // ["小蜜蜂", 30, "1 life"]
  Flyer.apply(this,arguments);//1.劫持另一个对象的方法,继承另一个对象的属性
            //this指向Bee,第二个参数后,都是i要传给Flyer的参数
  this.award=award;   //独特的属性: 
}

使用父类的构造函数来增强子类实例,等于是复制父类的实例属性给子类(没用到原型)

function Cat(fname,fspeed) {

  Flyer.call(this);

}

Bee.prototype.get=function(){
  console.log("获取对象独有的属性: "+this.award);
}

//2.让子类型的原型对象,继承父类型的原型对象---原型链继承

Object.setPrototypeOf(Bee.prototype,Flyer.prototype); //相当于Bee.__proto__=Flyer
var bee = new Bee("小蜜蜂",30,"1 life");
var flyer = new Flyer("蜜蜂",40,"1 life");
console.log(flyer); //Flyer {fname: "蜜蜂", fspeed: 40}
console.log(bee); //Bee {fname: "小蜜蜂", fspeed: 30, award: "1 life"}
bee.fly();
bee.get();

 

 

Js apply方法详解:http://www.360doc.com/content/13/0807/19/13328522_305431575.shtml

js中apply方法的使用: http://www.cnblogs.com/delin/archive/2010/06/17/1759695.html

 

JS实现继承的几种方式:http://www.cnblogs.com/humin/p/4556820.html

 

posted @ 2017-08-09 11:17  lijun8637  阅读(189)  评论(0编辑  收藏  举报