Previous Example-|-Next Example-|-Return to Chapter Listing

Example 13.4:
Creating an Object Prototype

[This example works with Netscape Navigator 3. It will not work properly with Internet Explorer 3.]

We've created a property (color) and a method (colored()) for String objects. Then we've used these to modify the way in which text is written to the page.


We have this script in the HEAD: <SCRIPT LANGUAGE="JavaScript"> <!-- var txt = new String("Here is some sample text.") String.prototype.color = "gray" function textColor() { return "<FONT color='" + this.color + "'>" + this + "</FONT>" } String.prototype.colored = textColor //--> </SCRIPT> Then this script in the BODY: <SCRIPT> <!-- document.write(txt + " (no color)<BR>") document.write(txt.colored() + " (default property color)<BR>") txt.color = "red" document.write(txt.colored() + " (red)<BR>") txt.color = "blue" document.write(txt.colored() + " (blue)<BR>") document.write("This also works with literals.".colored() + "<BR>") //--> </script>
Previous Example-|-Next Example-|-Return to Chapter Listing