当前位置:编程学习 > JS >>

js面向对象---继承

 

javaScript没有集成的对象,所以采用下面三种方法模拟:

 

 

1、js原型实现继承

function Person(name,age){

  this.name=name;

  this.age=age;

}

Person.prototype.sayHello=function(){

   document.write("使用原型得到Name:"+this.name+"</br>");

}

 

 //var per=new Person("zhangping","21");

  //per.sayHello();

 

 

 function Student(){}

 Student.prototype=new Person("zhangping","21");

 var stu=new Student();

 Student.prototype.gade="3";

  Student.prototype.intr=function(){

     document.write(this.gade);

 }

 stu.sayHello();

stu.intr();

*/

2、构造函数实现继承

/*

function  Parent(name){

   this.name=name;

   this.sayParent=function(){

     document.write("Parent:"+this.name);

   }

}

function  Child(name,age){

  this.tempMethod=Parent;

  this.tempMethod(name);

  /* www.zzzyk.com

  this.age=age;

  this.sayParent=function(){

     document.write("Child:"+this.name+"age:"+this.age);

   }

   */

   /*

}

var parent=new Parent("zhangping");

parent.sayParent();

var child=new Child("xiaoguanxianfei","11");

child.sayParent();

*/

 

3、使用Call Applay实现继承

 

function  Person(name,age,love){

    this.name=name;

    this.age=age;

    this.love=love;

    this.say=function say(){

       document.write("姓名:"+name);

    }

}

function student(name,age){

   Person.call(this,name,age);

}

function teacher(name,love){

   Person.apply(this,[name,love]);

}

var per=new Person("zhangping","21","guanxianfei");

per.say();

var stu=new student("guanxianfei","22");

stu.say();

var tea=new teacher("xiaoguanxianfei","22");

tea.say();

摘自 guanxianfei

补充:web前端 , JavaScript ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,