JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<button onclick="Native();">alert() puro</button>
<button onclick="nativeToString();">alert() como toString() nativo</button>
<button onclick="Stringfy();">alert() com JSON.stringify</button>
<button onclick="ToString();">alert() com ToString()</button>
<pre>Clique para ver...</pre>
CSS
button {
display: block;
width: 50%;
}
JavaScript
window.Native = function() {
var resultado = new MeuObjeto();
$("pre").html(String(resultado));
}
window.nativeToString = function() {
var resultado = new MeuObjeto().toString();
$("pre").html(String(resultado));
}
window.Stringfy = function() {
var resultado;
try {
resultado = JSON.stringify(new MeuObjeto());
}
catch (e) {
resultado = "ERROR: " + e.message;
}
$("pre").html(String(resultado));
}
window.ToString = function() {
var resultado = ToString(new MeuObjeto());
$("pre").html(String(resultado));
}
var MeuObjeto = function() {
this.prop1 = "Olá, Mundo!";
this.prop2 = "Hahahaha";
this.recursivo = this;
this.funcao = function() { return "retorno da função"; }
}
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 + '}]'...