标签:javascript 面向对象编程 js 继承
上一讲我们提出一个很好的思路,将一个类的可复用部分全部定义在prototype中,这样子类继承的时候可以很方便地通过prototype来继承;
但是也带来一个问题就是子类在重写prototype中的属性时会改变所有实例的属性,这是因为父类和子类实例都共享同一个prototype;
怎么解决呢?思路就是利用一个中间函数,具体请看代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>临时函数F</title> </head> <body> <script type="text/javascript"> function Shape(){ } Shape.prototype.name = 'shape'; Shape.prototype.toString = function() {return this.name;}; function TwoDShape(){ } //用中间函数先继承基类 var F = function(){} F.prototype=Shape.prototype; //子类继承中间函数 TwoDShape.prototype = new F(); TwoDShape.prototype.constructor = TwoDShape; //这是真正的重写 TwoDShape.prototype.name = '2D shape'; function Triangle(side, height) { this.side = side; this.height = height; this.getArea = function(){return this.side * this.height / 2;}; } var F = function(){} F.prototype=TwoDShape.prototype; Triangle.prototype = new F(); Triangle.prototype.constructor = Triangle; //重写 Triangle.prototype.name="Triangle"; var my = new Triangle(5, 10); /* alert(my.getArea()); alert(my.toString());//自己没有toString方法,继承而来 alert(my.constructor); alert(my instanceof TwoDShape);//有继承的特性 alert(my instanceof Shape); */ alert(my.name); var shape = new Shape(); alert(shape.name);//正常了 </script> </body> </html>
标签:javascript 面向对象编程 js 继承
原文地址:http://blog.csdn.net/zhengwei223/article/details/42010989