JavaScript继承的几种方式解析

(一).对象冒充

概念:新的类冒充旧的类(旧的类必须采用构造函数的方式)

示例代码:

//父类

function people(name,age){

this.name = name;

this.age = age;

this.say = function(){

alert("My name is "+this.name);

};

}

//创建一个对象

var Wen = new people("xiaowen","21");

Wen.say();

//子类

function chinese_people(name,age){

this.A = people;//冒充people这个对象

this.A (name,age);//继承people

delete this.A;//必须删除继承.防止覆盖被继承的类的属性和方法

this.area = function(){

alert("I am in china");

};

}

//创建一个chinese_people对象

Var marry = new chinese_people("xiaoxiao","20");

marry.say();

marry.area();

alert(marry.name);

另外,对象冒充也支持多继承,这里不做详解。

(2).call方法

概念:

调用一个对象的一个方法,以另一个对象替换当前对象。 

function Rect(width, height){
    this.width = width;
    this.height = height;
    this.area = function(){return this.width*this.height;};
}
function myRect(width, height, name){
    Rect .call(this,width,height);//应用call方法
    this.name = name;
    this.show = function(){
    alert(this.name+” with area:”+this.area());
    }
}

(3)apply方法

    /*定义一个人类*/  

   function Person(name,age)  

  {  

       this.name=name;  

     this.age=age;  

    }  

   /*定义一个学生类*/  

    functionStudent(name,age,grade)  

     {  

      //this在创建对象的 时候是Student

      //arguments:参数数组,即["name","age","grade"]

        Person.apply(this,arguments);  

         this.grade=grade;  

    }  

     //创建一个学生类  

    var student=new Student("qian",21,"一年级");  

    //测试  

    alert("name:"+student.name+"\n"+"age:"+student.age+"\n"+"grade:"+student.grade);  


(4).原型模式

概念:

是指利用了prototype或者说以某种方式覆盖了prototype,从而达到属性方法复制的目的。

prototype网上的三种理解:

     1:通过构造函数创建的普通对象,通过其constructor属性引用它的构造函数对象,从而间接引用(拥有)了构造对象中的prototype对象; 

    2:构造函数创建对象时,copy prototype中的属性和代码给所创建的对象。从而使创建的对象拥有了prototype中的所有功能和属性; 
    3:构造函数在创建对象时,把构造函数中的prototype引用赋给创建的普通对象;也就是说由构造函数创建的对象,都有一个指针指向prototype对象; 

function Person(){
    this.name = “Mike”;
    this.sayGoodbye = function(){alert(“GoodBye!”);};
}

Person.prototype.sayHello = function(){alert(”Hello!”);};

function Student(){}
Student.prototype = new Person();

 


function Person(name){
    this.name = name;
}

function Student(name,id){
    this.id = id;
}

Student.prototype = new Person(this.name);

 



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值