JavaScript 对象继承


原型继承:

  这种原型继承的特点:既继承了父类的模板,又继承了父类的原型对象。优点是继承了父类的模板,
    又继承了父类的原型对象,缺点就是父类实例传参,不是子类实例化传参,不符合常规语言的写法。

 1 function animal(footnum,eyescolor,feathercolor){ //夫类
 2   this.foot = footnum;
 3   this.eyes = eyescolor;
 4   this.feather = feathercolor;
 5 }
 6 animal.prototype.eat = function(){
 7   alert("eatting");
 8 }
 9 
10 function bird(){ //子类
11 
12 }
13 bird.prototype.fly=function(){
14   alert('fly');
15 }
16 bird.prototype = new animal(5,"black","red"); //继承
17 
18 var eagle = new bird(); //对象
19 eagle.eat();

类继承:

  继承了父类的模板,不继承了父类的原型对象。优点是方便了子类实例传参,
  缺点就是不继承了父类的原型对象

 1 function Person(name,age,tall){
 2   this.name = name;
 3   this.age = age;
 4   this.tall = tall;
 5 }
 6 Person.prototype.gether = function(){
 7   alert("gether");
 8 }
 9 
10 function boy(name,age,tall,face){
11 //call/apply Person.apply(this,[name,age,tall]);
12   Person.call(this);
13   this.face = face;
14 }
15 boy.prototype.play = function(){
16   alert("playing");
17 }
18 
19 var boys = new boy("小明",12,160,"circle");
20 boys.play();

组合继承:(推荐)

  既继承了父类的模板,又继承了父类的原型对象。优点方便了子类实例传参,
  缺点就是Boy.pertotype = new Persion() 函数又实例一次,函数内部变量又重复实例一次,
  大程序时候会很好性能。

 1 // 父类 
 2 function Person(name,age){ 
 3   this.name = name; 
 4   this.age = age; 
 5 }
 6 // 父类的原型对象属性 
 7 Person.prototype.id = 10;
 8 // 子类 
 9 function Boy(name,age,sex){ 
10 //call apply 实现继承
11 Person.call(this,name,age);
12   this.sex = sex;
13 }
14 // 原型继承实现 参数为空 代表 父类的实例和父类的原型对象的关系了
15 Boy.prototype = new Person();
16 var b = new Boy('c5',27,'男'); 
17 alert(b.name)// c5 
18 alert(b.id)//10

猜你喜欢

转载自www.cnblogs.com/NExt-O/p/9757853.html