Object prototype example

DescriptionJavascript snippet by - 11/22/10

This is an example of a javascript object prototype. You are basically adding another method to the String object. In this case we will add some simple styling to the prototype. We take the String object and add a core method to it that will turn any string created after declaring this prototype into a Bold,Green, and Uppercase String.

First create your testString, then write it to the dom and call the new method using dot syntax. There you go, a styled string. More importantly, the usefulness of this technique is astounding so use this example to learn about prototypes.

Tags

<script type="text/javascript">        
        
String.prototype.toBoldGreenCaps = function(){
	var rawString = this;
	rawString = rawString.bold();
	rawString = rawString.fontcolor('green');
	finalString = rawString.toUpperCase();
	return finalString;
}

var testString = "My test string to format - toBoldGreenCaps()";
document.write(testString.toBoldGreenCaps());
	
</script>
  • Share
Authored by: Adam J Nowak
http://hyperspatial.com

Comments and Feedback