Monday, January 10, 2011

JavaScript OOP using Prototype

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:
1:  <html>  
2:  <head>  
3:  <script type="text/javascript" language="javascript">  
4:  function NumberManip()  
5:  {  
6:   var result = 0;  
7:  }  
8:  NumberManip.prototype.add = function(num1, num2) {  
9:   this.result = num1 + num2;  
10:  }  
11:  NumberManip.prototype.subtract = function(num1, num2) {  
12:   this.result = num1 - num2;  
13:  }  
14:  //define toString(), similar to C# overriding ToString() function  
15:  NumberManip.prototype.toString = function()  
16:  {  
17:   return this.result;  
18:  }  
19:  function UseOOPScript()  
20:  {  
21:   var onj = new NumberManip();  
22:   onj.add(5,5);  
23:   var onj1 = new NumberManip();  
24:   onj1.subtract(6,3);  
25:   alert("Result of addition: " + onj + " Subtraction: " + onj1 + "");  
26:  }  
27:  </script>  
28:  </head>  
29:  <body>  
30:  <div>  
31:    <input type="submit" onclick="UseOOPScript()" value="Submit" />  
32:  </div>  
33:  </body>  
34:  </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.

0 comments:

Post a Comment