This Javascript program demonstrates methods for inheriting a class of type. In the first example, the CRealNumber is extended by the CComplexNumber class. A class that is extended must create an instance of the base class when it instantiated. On the other hand, the prototype property allows us to inherit a specific instance of an object. The prototype is more confusing by more flexible. For example, a single object can be used as the prototype of a group of objects so that they can all share a base instance.
<!DOCTYPE html> <html> <head> <title>XoaX.net's Javascript</title> </head> <body> <script type="text/javascript" src="InheritanceMethods.js"></script> </body> </html>
// Start this here class CRealNumber { constructor(dValue) { this.mdReal = dValue; } Magnitude() { return Math.abs(this.mdReal); } } class CComplexNumber extends CRealNumber { constructor(dReal, dImag) { super(dReal); this.mdImag = dImag; } Magnitude() { return Math.sqrt(this.mdReal*this.mdReal + this.mdImag*this.mdImag); } } function CVector2D(dX, dY) { this.mdY = dY; this.Magnitude = function () { return Math.sqrt(this.prototype.mdReal*this.prototype.mdReal + this.mdY*this.mdY); } this.prototype = new CRealNumber(dX); } var qVector3D = { mdZ : 4.0, Magnitude : function () { return Math.sqrt(this.prototype.prototype.mdReal*this.prototype.prototype.mdReal + this.prototype.mdY*this.prototype.mdY + this.mdZ*this.mdZ); } } var qReal = new CRealNumber(3); var qComplex = new CComplexNumber(-2, 1); var qVector2D = new CVector2D(3.6, 2.3); qVector3D.prototype = qVector2D; document.write("<hr />"); PrintAnObject(qReal); document.write("<hr />"); PrintAnObject(qComplex); document.write("<hr />"); PrintAnObject(qVector2D); PrintAnObject(qVector2D.prototype); document.write("<hr />"); PrintAnObject(qVector3D); PrintAnObject(qVector3D.prototype); PrintAnObject(qVector3D.prototype.prototype); document.write("<hr />"); document.writeln("Magnitude = " + qReal.Magnitude() + "<br />"); document.writeln("Magnitude = " + qComplex.Magnitude() + "<br />"); document.writeln("Magnitude = " + qVector2D.Magnitude() + "<br />"); document.writeln("Magnitude = " + qVector3D.Magnitude() + "<br />"); // This function just prints out the members of an object. function PrintAnObject(qObject) { var iCount = 0; var sOutput = typeof(qObject)+": " + qObject.constructor.name + "<br />"; for (var sProperty in qObject) { sOutput += " " + sProperty + ': ' + qObject[sProperty]+"<br />"; ++iCount; if (iCount >= 15) { document.writeln(sOutput); document.writeln(" ...<br />"); return; } } document.writeln(sOutput); }
© 20072025 XoaX.net LLC. All rights reserved.