This JavaScript example demonstrates how to instantiate or create a new object via four different methods.
<!DOCTYPE html>
<html>
<head>
<title>XoaX.net's Javascript</title>
</head>
<body>
<script type="text/javascript" src="InstantiationMethods.js"></script>
</body>
</html>// 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); } // Object type 1 - Using an object literal var qObjectType1 = { mdRe : .5, mdIm : .866, mfnMag : function() { return Math.sqrt(this.mdRe*this.mdRe + this.mdIm*this.mdIm); } }; document.write("Magnitude of ObjectType1 = " + qObjectType1.mfnMag() + "<br />"); // Print the members of the object PrintAnObject(qObjectType1); document.write("<hr />"); // Object type 2 - Using new Object() // This is functionally equivalent to // var qObjectType2 = {}; var qObjectType2 = new Object(); // The we can add properties or methods. In JavaScript, we can add properties and methods to any object. qObjectType2.mdX = 2.3; qObjectType2.mdY = -1.8; qObjectType2.mfnMag = function() { return Math.sqrt(this.mdX*this.mdX + this.mdY*this.mdY); } document.write("Magnitude of ObjectType2 = " + qObjectType2.mfnMag() + "<br />"); // Print the members of the object PrintAnObject(qObjectType2); document.write("<hr />"); // Object type 3 - Using a constructor function function CPoint3D(dX, dY, dZ) { this.mdX = dX; this.mdY = dY; this.mdZ = dZ; this.mfnDist = function() { return Math.sqrt(this.mdX*this.mdX + this.mdY*this.mdY + this.mdZ*this.mdZ); } } var qObjectType3 = new CPoint3D(3.1, 1.2, 2.5); document.write("Distance to ObjectType3 = " + qObjectType3.mfnDist() + "<br />"); // Print the members of the object PrintAnObject(qObjectType3); document.write("<hr />"); // Object type 4 - Using a class and its constructor class CVector3D { constructor(dI, dJ, dK) { this.mdI = dI; this.mdJ = dJ; this.mdK = dK; } Magnitude() { return Math.sqrt(this.mdI*this.mdI + this.mdJ*this.mdJ + this.mdK*this.mdK); } } var qObjectType4 = new CVector3D(1.4, 3.1, 2.3); document.write("Magnitude of ObjectType4 = " + qObjectType4.Magnitude() + "<br />"); // Print the members of the object PrintAnObject(qObjectType4); document.write("<hr />");
© 20072025 XoaX.net LLC. All rights reserved.