This Javascript program demonstrates simple inheritance. The CAShape class is a sort of prototypical example of an abstract class that contains some simple methods and a property that gets inherited. The Draw() method is a sort of interface method, but JavaScript does not have that same mechanism. In this case, the Draw() method is overridden, but it is not strictly necessary.
Inside the CAShape class, the property msStrokeColor is declared with a pound sign to indicate that it is private. This means that it can not be directly accessed outside the CAShape class. However, he public get() and set() methods effectively make the property msStrokeColor public. However, within the get() and set() methods we can put additional controls on the access of msStrokeColor, if we choose to do so.
<!DOCTYPE html> <html> <head> <title>XoaX.net's Javascript</title> <script type="text/javascript" src="Inheritance.js"></script> </head> <body onload="Initialize()"> <canvas id="idCanvas" width="640" height ="480" style="background-color: #F0F0F0;"></canvas> </body> </html>
// This should be an abstract class, but JavaScript doesn't support them. class CAShape { #msStrokeColor; constructor() { this.#msStrokeColor = "black"; } // Inherited get and set methods get StrokeColor() { return this.#msStrokeColor; } set StrokeColor(sColor) { this.#msStrokeColor = sColor; } // Due to nature of JavaScript, interface methods like this one are not needed. Draw(qCanvas) {} } class CLine extends CAShape { constructor(dX1, dY1, dX2, dY2) { // The parent constructor must be called first. super(); this.mdX1 = dX1; this.mdY1 = dY1; this.mdX2 = dX2; this.mdY2 = dY2; } Draw(qCanvas) { var qContext = qCanvas.getContext("2d"); qContext.globalAlpha = 1.0; qContext.strokeStyle = this.StrokeColor; qContext.beginPath(); qContext.moveTo(this.mdX1, this.mdY1); qContext.lineTo(this.mdX2, this.mdY2); qContext.stroke(); } } function Initialize() { var qCanvas = document.getElementById("idCanvas"); var qLine1 = new CLine(100, 50, 500, 75); var qLine2 = new CLine(150, 350, 400, 20); var qLine3 = new CLine(50, 300, 600, 380); qLine1.Draw(qCanvas); // Set the second line color to red qLine2.StrokeColor = "red"; qLine2.Draw(qCanvas); // Copy the color from the second line qLine3.StrokeColor = qLine2.StrokeColor; qLine3.Draw(qCanvas); }
© 20072025 XoaX.net LLC. All rights reserved.