Name: Object.toString() examples
Author: senocular: www.senocular.com
Date: 1899-12-31T00:34:10.600
Documentation:
Object toSTRING: 2 methods of displaying objects as a string
or formatting trace output; one single-line and the other
multi-line. Use one or the other (as they are named the same).
Should you want both, just rename one. ;)
Arguments:
- technically none, but you can pass in an argument to represent a name identifier for
the outputs. exmaple:
myObj = {a:1, b:2, c:3};
trace(myObj.toString("bob: "));
//single line output:
bob: {a: 1, b: 2, c: 3}
// multiline output
bob: {
a: 1
b: 2
c: 3
}
Otherwise, single line will give no identifier and multiline will say "Object: ".
Returns:
- a formatted string representing your object and its contents.
Also see:
Object to ActionScript Utility:
http://proto.layer51.com/d.aspx?f=554
List All Objects:
http://proto.layer51.com/d.aspx?f=581
traceEx:
http://proto.layer51.com/d.aspx?f=725
Example:
Johnny = {Name:"Johnny", Age:12, Dental_Record:{Cavities:[16,21,3], Dentures:false, Make_Appointment: function(){ makeappnt(); }}, Child:"none"};
Sam = {Name:"Sam", Age:40, Dental_Record:{Cavities: "none", Dentures:true, Make_Appointment: function(){ makeappnt(); }}, Child:Johnny};
trace(Johnny); // singleline used
// output:
// {Name: Johnny, Age: 12, Dental_Record: {Cavities: [16,21,3], Dentures: false, Make_Appointment: (function)}, Child: none}
trace(Sam); // multiLine used
// output:
Object: {
Name: Sam
Age: 40
Dental_Record: {
Cavities: none
Dentures: true
Make_Appointment: (function)
}
Child: {
Name: Johnny
Age: 12
Dental_Record: {
Cavities: [16,21,3]
Dentures: false
Make_Appointment: (function)
}
Child: none
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
// Single-line:
Object.prototype.toString = function(s){
var looped = false;
s += "{";
for (var p in this){
if (!looped) looped = true
if (this[p] instanceof Array) s += p+": ["+this[p]+"], ";
else if (typeof this[p] == "object") s += this[p].toString(p+": ")+", ";
else if (typeof this[p] == "function") s += p+": (function), ";
else s += p+": "+this[p]+", ";
}
if (looped) return s.slice(0,-2)+"}";
return s+"}";
}
// =======================
// Multi-line:
Object.prototype.toString = function(s, t){
if (t == undefined) t = "\t";
else t += "\t";
if (s == undefined) s = "Object: {";
else s += "{";
for (var p in this){
s += "\n"+t;
if (this[p] instanceof Array) s += p+": ["+this[p]+"]";
else if (typeof this[p] == "object") s += this[p].toString(p+": ", t);
else if (typeof this[p] == "function") s += p+": (function)";
else s += p+": "+this[p];
}
return s+"\n"+t.slice(0,-1)+"}";
}