javascript 面向对象继承和泛型 记录

根据《JavaScript高级程序设计》 中的内容自己写的一个测试demo,记录一下

var Person = function(name){    
     this.Name=name;    
};
Person.prototype.sayHello=function(){alert(this.Name);};

//学生类,继承Person
  var Student = function(name,grade){ 
    Person.call(this,name);
    this.Grade=grade;    
    };
//使用原型呼叫基类,完成继承
Student.prototype = new Person();

Student.prototype.sayHello=function(){
 alert(this.Name+"-"+this.Grade);
};

//教师类,继承Person
 var Teacher = function(name,subject) {      
   Person.call(this,name);
   this.Subject=subject;   
    };
//使用原型呼叫基类,完成继承
 Teacher.prototype = new Person();
  Teacher.prototype.sayHello=function(){
   alert(this.Name+"-"+this.Subject);
};


  //多态在此
  function SayHello(intro) {   
     // 判断实参是否是Person的一个实例
     if (intro instanceof Person) {
      // 调用自我介绍方法(编译器会自动获取被覆盖过的子类方法并调用)
      intro.sayHello();
     }    
  }

    // 测试方法
 (function main(){     
     // 创建一个学员实例并设置
     var stu = new Student("张三","初中二年级");     
     // 创建一个教师实例并设置属性
     var tea = new Teacher("李四","3天精通Eca");     
    // 创建另一个教员实例并设置属性
     var tea2 = new Teacher("王五","java");    
    
     SayHello(stu);     
     SayHello(tea);
     SayHello(tea2);     
    })();

posted on 2012-07-25 11:07  Mr_Cod  阅读(293)  评论(0)    收藏  举报

导航