Javascript Oop
- 2. Introduction //adding a custom property to a prebuilt object var myimage=new Image() myimage.size="26k" /*adding a custom property to the custom object "circle"*/ //First, create the custom object "circle" function circle(){ } var smallcircle=new circle() smallcircle.pi=3.14159 It will not work when a new object will created from circle as not inherited to it.
- 3. Using the prototype object to add custom properties to objects //First, create the custom object "circle" function circle(){ } circle.prototype.pi=3.14159 This is javascript object that helps function to inherit new properties and methods
- 4. Using the prototype object to add custom methods to objects //First, create the custom object "circle" function circle(){ } circle.prototype.pi=3.14159 // create the object method. function alertmessage(){ alert(this.pi) } circle.prototype.alertpi=alertmessage
- 5. Example 1-Extending functionality to the pre-built string() object <script type="text/javascript"> /*code for extending String object with method that writes text backwards*/ //core custom method for writing text backwards function outputbackwards(){ for (i=this.length-1;i>=0;i--) document.write(this.charAt(i)) } /Attach custom method to string object String.prototype.writeback=outputbackwards var message1="Welcome to my site!" message1.writeback() var message2="Today is a beautiful day" message2.writeback() </script> Output: !etis ym ot emocleW yad lufituaeb a si yadoT
- 6. Example 2 Extending functionality to a custom JavaScript object <script type="text/javascript"> //create dummy object function dummy(){ } //Create custom property function dummyproperty(){ } //Create custom method function dummymethod(){ } dummy.prototype.prop=dummyproperty dummy.prototype.method=dummymethod </script>