JavaScript实现"继承"

来源:互联网 发布:python rsa 加密 编辑:程序博客网 时间:2024/06/01 07:45
实现方法:在javascript中没有继承的概念,ECMAScript中提出了原型链的概念,并将原型链作为实现继承的主要方式
基本思想:利用原型让一个自定义类继承另一个类的属性和方法
//定义父类personfunction person(n,a,p){this.name=n;this.age=a;this.phone=p;}//父类方法person.prototype.sayHello=function(){alert(this.name+"向你问好");}//定义子类studentfunction student(s){this.score=s;}//子类继承student.prototype=new person();//子类重写父类方法student.prototype.sayHello=function(){alert("学生"+this.name+"向你问好");}//声明子类独有的方法student.prototype.getDetials=function(){alert(this.name+"成绩"+this.score);}var s=new student();       s.name="张无忌";s.age="28";s.phone="123456";s.score=100;s.sayHello();s.getDetials();

子类利用父类构造方法为属性赋值:

function Person(n,a,p){this.name=n;this.age=a;this.phone=p;}Person.prototype.sayHello=function(){    alert(this.name+"向你问好!");}function Student(n,a,p,s){Person.call(this,n,a,p);//用Person来替换this(Student)//Person.call(this,n,a,p)==Person(n,a,p);this.score=s;}Student.prototype=new Person();Student.prototype.sayHello=function(){alert("学生"+this.name+"向你问好!");}Student.prototype.getDetials=function(){     alert(this.name+"的成绩是"+this.score);}var s=new Student("张无忌",28,"18638643721",100);s.sayHello();s.getDetials();