JavaScript обекно ориентирано програмиране – наследяване (пример)

Един много прост пример за наследяване на клас в JavaScript.
В случая имам клас Shape (форма), който ще разширя с клас за правоъгълник (Rectangle), който на свой ред ще разширя с клас за квадрат (Square).

<html>
<head>
<script type="text/javascript">
var Shape = function() {name: 'Shape'};
Shape.prototype.toString = function() {return this.name;};
 
var Rectangle = function(width, height) {this.width = width; this.height = height; this.shape = 'Rectangle';};
Rectangle.prototype = new Shape;
Rectangle.prototype.constructor = Rectangle;
Rectangle.prototype.area = function() {return this.width * this.height;};
 
var Square = function(width) {this.width = width; this.shape = 'Square';};
Square.prototype = new Rectangle();
Square.prototype.constructor = Square;
Square.prototype.area = function() {return this.width * this.width;};
 
myShape = new Square(6);
</script>
</head>
<body>
	myShape = new Square(6) ==&gt;<br/>
	<script type="text/javascript">document.write(myShape.width);</script>
</body>
</html>

==========================================================

По-горния код е интересен, но тъй като съм го копирал и преработвал, без много да му вниквам, не е мисля, че е добър.
Ето така го оптимизирах, след като попрочетох малко за ООП-то на JavaScript:

var Shape = function () {};
 
var Triangle = function(w, h) { this.width = w; this.heigh = h; }
Triangle.prototype = new Shape();
Triangle.prototype.getArea = function () {return this.width * this.heigh; };
 
// ====== Kvadrat
var Square = function (l) { this.width = l; this.heigh = l; };
Square.prototype = new Triangle();
 
// ======== Examples
 
var square = new Square(4),
    triangle = new Triangle(2, 5);
 
print(square.getArea());
print(triangle.getArea());

За да стартирам кода използвам SublimeText2 с инсталирана приставка за стартиране на команди от шела Turtlestein, а за JavaScript интерпретатор използвам SpiderMonkey 1.8.5 for Windows.

Share and Enjoy !

Shares

Leave a Reply

Your email address will not be published. Required fields are marked *

*