You can write this function to convert any object to string
.
See this JSFiddle sample function below
function ToString(obj) {
clearTimeout(window.ToStringTimeout);
var result;
var ident = arguments.length >= 2 ? arguments[1] : undefined;
if (obj == null) {
result = String(obj);
}
if (!result) {
window.ToStringRecursive = window.ToStringRecursive ? window.ToStringRecursive : [];
if (ToStringRecursive.indexOf(obj) >= 0) {
result = obj ? (typeof(obj) == "string" ? "\"" + obj + "\"" : obj.toString()) : obj;
} else {
ToStringRecursive.push(obj);
}
if (!result) {
switch (typeof obj) {
case "string":
result = '"' + obj + '"';
break;
case "function":
result = obj.name || obj.toString();
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 = obj.toString();
break;
}
}
}
window.ToStringTimeout = setTimeout(function() {
delete window.ToStringTimeout;
delete window.ToStringRecursive;
}, 100);
return result;
}
Test using this:
console.log(ToString(new MyObject()));
To display this:
{
prop1: "Olá, Mundo!",
prop2: "Hahahaha",
recursivo: [object Object],
funcao: function () { return "retorno da função"; }
}
See that when a property is recursive it is not displayed again because it would loop endlessly.