JavaScript面向对象---继承

来源:互联网 发布:恒源软件 编辑:程序博客网 时间:2024/04/29 16:56
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); 
  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();
原创粉丝点击