Donate

JavaScript Object Oriented Programming Using Prototype

Hello,

In JavaScript, each Object can inherit properties from another object, called it's prototype. When evaluating an expression to retrieve a property, JavaScript first looks to see if the property is defined directly in the object. If it is not, it then looks at the object's prototype to see if the property is defined there. This continues up the prototype chain until reaching the root prototype. Each object is associated with a prototype which comes from the constructor function from which it is created. (Source: http://mckoss.com/jscript/object.htm)

Here's an example i created:
  <html>  
  <head>  
  <script type="text/javascript" language="javascript">  
	  function NumberManip()  
	  {  
	   var result = 0;  
	  }  
	  NumberManip.prototype.add = function(num1, num2) {  
	   this.result = num1 + num2;  
	  }  
	  NumberManip.prototype.subtract = function(num1, num2) {  
	   this.result = num1 - num2;  
	  }  
	  //define toString(), similar to C# overriding ToString() function  
	  NumberManip.prototype.toString = function()  
	  {  
	   return this.result;  
	  }  
	  function UseOOPScript()  
	  {  
	   var onj = new NumberManip();  
	   onj.add(5,5);  
	   var onj1 = new NumberManip();  
	   onj1.subtract(6,3);  
	   alert("Result of addition: " + onj + " Subtraction: " + onj1 + "");  
	  }  
  </script>  
  </head>  
  <body>  
  <div>  
    <input type="submit" onclick="UseOOPScript()" value="Submit" />  
  </div>  
  </body>  
  </html>  

Based from the code above, we created two objects onj and onj1. After that, each object references to a method of NumberManip. The NumberManip acts
as a constructor when you declared onj and onj1 objects.

Comments

Donate

Popular Posts From This Blog

WPF CRUD Application Using DataGrid, MVVM Pattern, Entity Framework, And C#.NET

How To Insert Or Add Emojis In Microsoft Teams Status Message

TypeScript Error Or Bug: The term 'tsc' is not recognized as the name of a cmdlet, function, script file, or operable program.