简述:
关于javascript 继承的实现
知识点:
1. 继承父类的方法
2. 使用prototype定义类的成员函数
3. 子类重写父类的成员函数
测试:
1.继承父类,包括父类的成员函数
代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>test the inheritance</title> </head> <body> <script type="text/javascript"> /*************************Person class*************************/ var Person = function(name,age){ this.name = name; this.age = age; }; Person.prototype.getInfo = function(){ return "name: " + this.name + ", age: " + this.age; }; /*************************Employee class*************************/ // inherit Person class var Employee = function(name,age,job){ Person.call(this,name,age); this.job = job; } //if Employee wants to inherit Person //the prototype should be the father Employee.prototype = new Person(); /*****************************test********************************/ var employee = new Employee("Peter",21,"worker"); document.write(employee.getInfo()); </script> </body> </html>
输出:
name: Peter, age: 20
2.继承父类后,重写父类成员函数
重写父类的getInfo()函数
代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>test the inheritance</title> </head> <body> <script type="text/javascript"> /*************************Person class*************************/ var Person = function(name,age){ this.name = name; this.age = age; }; Person.prototype.getInfo = function(){ return "name: " + this.name + ", age: " + this.age; }; /*************************Employee class*************************/ // inherit Person class var Employee = function(name,age,job){ //invoke the constructor of base class Person.prototype.constructor.call(this,name,age); this.job = job; } //if Employee wants to inherit Person //the prototype should be the father Employee.prototype = new Person(); //overwrite member function in Person Employee.prototype.getInfo = function(){ return "name: " + this.name + ", age: " + this.age +", job: " + this.job; } /*****************************test********************************/ var employee = new Employee("Peter",21,"worker"); document.write(employee.getInfo()); </script> </body> </html>
name: Peter, age: 21, job: worker