javascript中的继承

js中定义类或对象一般使用“构造函数+原型”方式:用构造函数定义所有非方法的成员,用原型定义方法成员

 js中的继承有三种方法,对象冒充,原型链,对象冒充+原型链

/**  1、对象冒充   将Parent中执行的this绑定到对象child上
//写法1
function Parent(){
    this.name="parent";
 this.sayName = function (){
   alert("I am "+this.name);
 }
}

 function Child(){
   
   this.name="child";
}

  var child = new Child();
  Parent.call(child);
  child.sayName(); 
//写法2
function Parent(){
   this.name= "parent";
   this.sayName = function (){
        alert(" I am "+this.name);
   }
}
function Child (){
    this.age="26";
 Parent.call(this);
}
var child  = new Child();
child.sayName();
alert(child.name+"  "+child.age);

 

/** 2、 原型链  */
 function Parent (){
    this.name = "parent";
 this.age = "54";
 }

 function Child1 (){
    this.name = "child1"
    this.point = "北京";
 this.salary = "3500";
 }
Child1.prototype = new Parent();//
var child1 = new Child1();
alert(child1.name+"   "+child1.point+"  "+child1.salary);

function Child2(){
 this.point = "哈尔滨";
 this.salary = "5000";
}
Child2.prototype = new Parent();

var child2 = new Child2();
alert(child2.name+"  "+child2.point+"   "+child2.salary);

 /**  3、对象冒充+原型链 */

//实现继承一般使用“对象冒充(object masquerading)+原型链”方式:用对象冒充继承构造函数的所有成员,用原型链继承原型的方法(用了原型链,instanceOf运算符才有效)。

 Animal.prototype.ShowName =  function() {
     alert(this.name);
 }

 function Animal(animalName){
   this.name = animalName;
 
 }

 function Bird(birdName,birdColor){
     Animal.call(this,birdName);
  this.color = birdColor;
 }
 Bird.prototype = new Animal();
 Animal.prototype.age = "10";
 Bird.prototype.ShowColor = function (){
     alert(this.color);
 }

 var bird = new Bird("gugu","red");
 bird.ShowName();
 bird.ShowColor();
 alert(bird.age);

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值