JavaScript 1.3 Overview, Part I: toSouce() Method - Doc JavaScript | WebReference

JavaScript 1.3 Overview, Part I: toSouce() Method - Doc JavaScript


toSource Method

JavaScript 1.3 defines the toSource(), a new method for all built-in objects. This function returns the object's definition, exactly as it has been specified by the author. It is similar to the toString() method of the Object and Array objects. If for the Array object, both methods yield similar results about the array elements, their output is very different for the Object object. While the toString() method returns a useless result ([object object]) for the Object object, the toSource() method returns a detailed replica of the object definition by the author. The example below demonstrates this behavior.

The following code segment defines several objects and runs both toString() and toSource() on them:


bankAccount = {name: "Bill Clinton", sum: 3000, type: "credit"};
shoppingList = ["bread", 2, "milk", 4, "eggs", 12];
myBool = new Boolean;
myString = new String("it is a beautiful day outside");
myData = new Date();
document.write("bankAccount.toSource = " + bankAccount.toSource() + "
"); document.write("bankAccount.toString = " + bankAccount.toString() + "
"); document.write("shoppingList.toSource = " + shoppingList.toSource() + "
"); document.write("shoppingList.toString = " + shoppingList.toString() + "
"); document.write("myBool.toSource = " + myBool.toSource() + "
"); document.write("myBool.toString = " + myBool.toString() + "
"); document.write("myString.toSource = " + myString.toSource() + "
"); document.write("myString.toString = " + myString.toString() + "
"); document.write("myData.toSource = " + myData.toSource() + "
"); document.write("myData.toString = " + myData.toString() + "
");

Here is the output:


bankAccount.toSource = {name:"Bill Clinton", sum:3000, type:"credit"}
bankAccount.toString = [object Object]
shoppingList.toSource = ["bread", 2, "milk", 4, "eggs", 12]
shoppingList.toString = bread,2,milk,4,eggs,12
myBool.toSource = (new Boolean(false))
myBool.toString = false
myString.toSource = (new String("it is a beautiful day outside"))
myString.toString = it is a beautiful day outside
myData.toSource = (new Date(905292116880))
myData.toString = Wed Sep 09 00:05:33 GMT+0200 (Israel Standard Time) 1998

The first two lines compares the two functions w/r/t to a generic object. toString() just echoed the fact that it is an object.toSource() echoed the author's definition to the letter. In all other cases, toString() yields the result of the method, while toSource regenerates the original author's definition.

http://www.internet.com


Created: September 14, 1998
Revised: September 14, 1998

URL: http://www.webreference.com/js/column25/tosource.html