You can write this function and convert any object to string
.
Look JSFiddle
////For NodeJS remove comment below:
//var window = { };
function ToString(obj) {
clearTimeout(window.ToStringTimeout);
var result;
var ident = arguments.length >= 2 ? arguments[1] : undefined;
if (obj == null) {
result = String(obj);
}
var objString;
try {
objString = obj.toString();
} catch (err1) {
try {
objString = String(obj);
} catch (err2) {
try {
objString = obj + "";
} catch (err3) {
objString = "ERROR CONVERT STRING";
}
}
}
if (!result) {
window.ToStringRecursive = window.ToStringRecursive ? window.ToStringRecursive : [];
if (window.ToStringRecursive.indexOf(obj) >= 0) {
result = obj ? (typeof(obj) == "string" ? "\"" + obj + "\"" : objString) : obj;
} else {
window.ToStringRecursive.push(obj);
}
if (!result) {
switch (typeof obj) {
case "string":
result = '"' + obj + '"';
break;
case "function":
result = obj.name || objString;
break;
case "object":
var indent = Array(ident || 1).join('\t'),
isArray = Array.isArray(obj);
result = '{[' [+isArray] + Object.keys(obj).map(
function(key) {
return '\n\t' + indent + key + ': ' + ToString(obj[key], (ident || 1) + 1);
}).join(',') + '\n' + indent + '}]' [+isArray];
break;
default:
result = objString;
break;
}
}
}
window.ToStringTimeout = setTimeout(function() {
delete window.ToStringTimeout;
delete window.ToStringRecursive;
}, 100);
return result;
}
And use this:
console.log(ToString(new MyObject()));
To show this:
{
prop1: "Hello World",
prop2: "LOL",
recursive: [object Object],
func: function () { return "func return"; }
}
Observe... when any property is recursive this not show again, because this is infinite.