JavaScript 1.3 Overview, Part II: Changes to the toString Method - Doc JavaScript
Changes to the toString Method
JavaScript 1.3 changed the behavior of the toString()
method. If you parse the output of this method, be ready to change your code to be 1.3-compliant.
When operating on the Object
object, the toString()
method in JavaScript 1.2 returned the object's properties and values. The object was x-rayed. Let's take our assembly line example from previous pages:
<HTML>
<HEAD>
<TITLE> two-object constructors </TITLE>
</HEAD>
<BODY>
<SCRIPT LANGUAGE="JavaScript">
<!--
function exterior(extColor, doorCount, airWing, tireWidth) {
this.extColor = extColor;
this.doorCount = doorCount;
this.airWing = airWing;
if (tireWidth > 10)
this.wideTire = true;
else
this.wideTire = false;
}
function interior(intColor, seatCoverType, benchOption) {
this.intColor = intColor;
this.seatCoverType = seatCoverType;
this.bench = benchOption;
}
volvoInterior = new interior("blue", "leather", true);
document.write(volvoInterior.toString());
// -->
</SCRIPT>
</BODY>
</HTML>
The output of the document.write
statement is:
{intColor:"blue", seatCoverType:"leather", bench:true}
If you change the JavaScript version in the SCRIPT
tag to 1.3, the output will be:
[object Object]
In general, the output is [object type]
, where type
is the name of the object type, such as Image
, Form
, and Document
. If the type
is defined by the user, as in our assembly line's volvoInterior
object, the string Object
is printed instead of the object's type.
The toString()
method of the Array
object changed as well, but less significantly than the Object
's one. In JavaScript 1.2, the toString()
method returned a string containing the array elements inside a pair of brackets. A blank and a comma separated neighboring elements. The following script segment:
a = new Array(1, 5, 7, 10);
document.write(a.toString());
printed the following output:
[1, 5, 7, 10]
JavaScript 1.3's output is much shorter. It does not have the brackets and the blanks between the elements. The output of the above script would be:
1,5,7,10
If you store the above output in a string and test its length, you will get a length of 13 characters in JavaScript 1.2 as opposed to a length of 8 characters in JavaScript 1.3
Created: September 28, 1998
Revised: September 28, 1998
URL: https://www.webreference.com/js/column26/tostring.html