Showing posts with label Prototype. Show all posts
Showing posts with label Prototype. Show all posts

That means prototype helps us to extend the basic built in types by adding additional properties depending on our need.


For example for strings you may want to define a new method for converting a string into new type of html font tag not already defined by javascript object.



<html>

<head>

    <title>Javascript Prototype Object</title>

<script type="text/javascript">

function GetFontHTM()

{

return "<font color='blue'>"+this.toString()+"</font>";

}

String.prototype.gethtm=GetFontHTM;


</script>

</head>

<body>

<div id="test">


</div>

<script>

var divid=document.getElementById("test");

divid.innerHTML="Test".gethtm();

</script>


</body>


</html>





 




Another example is shown below


Even though a Car class does not define a property named mileage, we were able to create

one for the mySUV object simply by assigning a value to it. Since we applied this property to

the mySUV object and not the Car class, other objects derived from the Car class will not have

a mileage property


Extend an Existing Object


Just as a class can be extended using the prototype property, objects themselves can have new

properties and methods attached to them.





function Car (make, model, year, color) {

this.Make = make;

this.Model = model;

this.Year = year;

this.Color = color;

this.FullName = this.Year + " " +

"<b>" + this.Make + "</b> " +

this.Model;

}




var mySUV = new Car("Toyota", "4Runner SR5",2001, "Thundercloud");

mySUV.mileage = 12323;

document.write(mySUV.FullName + " has traveled " +mySUV.mileage + " miles.<br><br>");