Javascript doesn’t make much difference between a string value and a string object. Both allow you to use the same methods in your content, so in general you don’t have to create a string object every time you want to assign a string value to a variable. A simple assignment operation (var palavra = 'Palavra';
) is all you need to create a string value that behaves, on the surface, very similar to a full string object.
The difference appears exactly when you want to explore the "object side" of a genuine string object.
Strings objects defined with the constructor new String("valorString")
are powerful objects compared to simple variables, which receive string values. You certainly don’t need to create this type of object for each string in your scripts, but they are very practical if you find that the strings in the variables are wrong. This happens occasionally while trying to preserve string information as script variables in other frames or windows. Using the string object constructor, you can be relatively sure that the string value will be available in the far frame when needed.
Another by-product of true string objects is that you can position prototype properties and methods to all string objects in the document. A prototype is a property or method that becomes part of each new object created after the prototype items are added. For strings, for example, you may want to define a new method to convert a string into a new type of HTML font tag, not yet defined by the Javascript string object.
The following is shown how to create and use this type of prototype.
<HTML>
<HEAD>
<TITLE>String Object Prototype</TITLE>
<SCRIPT LANGUAGE="JavaScript1.1">
function makeItHot() {
return "<span style='color:red'>" + this.toString() + "</span>"
}
String.prototype.hot = makeItHot
</SCRIPT>
<BODY>
<SCRIPT LANGUAGE="JavaScript1.1">
document.write("<H1>This site is on " + "FIRE".hot() + "!!</H1>")
</SCRIPT>
</BODY>
</HTML>
The result is as follows:
function makeItHot() {
return "<span style='color:red'>" + this.toString() + "</span>"
}
String.prototype.hot = makeItHot
document.write("<H1>This site is on " + "FIRE".hot() + "!!</H1>")