一、在构造函数中定义属性
二、在原形对象中定义共享方法
完整实例:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script language="javascript"> function sc(name,age,score) { //定义构造函数 this.name = name this.age = age this.score = score } sc.prototype.display_score = function (){ //定义共享方法 document.writeln("姓名:",this.name," ") document.writeln("年龄:",this.age," ") document.writeln("分数:",this.score,"<br>") } var s = new sc("张三",20,100) //实例化一个对象,必须用new关键字 s.display_score() //调用共享方法 function SC(name,age,sex,score) { //(封装) //定义子类构造函数,继承自sc sc.call(this,name,age,score); this.sex = sex } SC.prototype = new sc() //(继承) var S = new SC("李四",21,"男",100); S.display_score()//调用父类的display_score() //重定义子类自己的display_score() (多态) SC.prototype.display_score = function () { document.writeln("姓名:",this.name," ") document.writeln("年龄:",this.age," ") document.writeln("性别:",this.sex," ") document.writeln("分数:",this.score,"<br>") } S.display_score() //调用子类的display_socre() </script> </body> </html>
输出结果:
姓名:张三 年龄:20 分数:100 姓名:李四 年龄:21 分数:100 姓名:李四 年龄:21 性别:男 分数:100