| [ Web Proxy ] |
| Viewing: https://developer.mozilla.org/pt-BR/docs/Web/JavaScript/Reference/Global_Objects/Object/toString | [Back] [Original] |
Get to know MDN better
Esta pgina foi traduzida do ingls pela comunidade. Saiba mais e junte-se comunidade MDN Web Docs.
This feature is well established and works across many devices and browser versions. Its been available across browsers since julho de 2015.
O mtodo toString() retorna uma string representando o objeto.
function Dog(name) {
this.name = name;
}
const dog1 = new Dog("Gabby");
Dog.prototype.toString = function dogToString() {
return `${this.name}`;
};
console.log(dog1.toString());
// Expected output: "Gabby"
obj.toString();
Todo objeto possui um mtodo toString() que chamado automaticamente quando o objeto precisa ser representado como um valor em texto ou quando o objeto referenciado de uma maneira que requeira uma string. Por padro, o mtodo toString() herdado de todo objeto descendente de Object. Se e o mtodo no sobrescrito em um objeto personalizado, toString() retorna "[object type]", onde type o tipo do objeto. O cdigo a seguir ilustra isso:
var o = new Object();
o.toString(); // retorna [object Object]
Nota:
Starting in JavaScript 1.8.5 toString() called on null returns [object Null], and undefined returns [object Undefined], as defined in the 5th Edition of ECMAScript and a subsequent Errata. See Using toString to detect object type.
toStringVoc pode criar uma funo para ser chamada no lugar do mtodo toString(). O mtodo toString() no requer parmetros e deve retornar uma string. O mtodo toString() criado por voc pode ter o valor que quiser, mas ser mais til se usar informaes do objeto.
O cdigo abaixo define o objeto Dog e cria theDog, um objeto do tipo Dog:
function Dog(name, breed, color, sex) {
this.name = name;
this.breed = breed;
this.color = color;
this.sex = sex;
}
theDog = new Dog("Gabby", "Lab", "chocolate", "female");
Se voc chamar o mtodo toString() neste objeto, ele retornar o valor original herdado de Object:
theDog.toString(); // returns [object Object]
O cdigo abaixo cria e faz com que dogToString() sobrescreva o toString() original. Esta funo gera uma string contendo name, breed, color, and sex do objeto, na forma de "propriedade = valor;".
Dog.prototype.toString = function dogToString() {
var ret =
"Dog " +
this.name +
" is a " +
this.sex +
" " +
this.color +
" " +
this.breed;
return ret;
};
Usando este cdigo, toda vez que theDog for usado em um texto (string), JavaScript automaticamente chamar a funo dogToString(), a qual retornar:
Dog Gabby is a female chocolate Lab
toString() para detectar a classe do objetotoString() pode ser usado com qualquer objeto e permite que voc determine sua classe. Para usar Object.prototype.toString() com qualquer objeto, dever chamar Function.prototype.call() ou Function.prototype.apply() nele, passando o objeto que quer inspecionar como o primeiro parmetro, chamado thisArg.
var toString = Object.prototype.toString;
toString.call(new Date()); // [object Date]
toString.call(new String()); // [object String]
toString.call(Math); // [object Math]
// Since JavaScript 1.8.5
toString.call(undefined); // [object Undefined]
toString.call(null); // [object Null]
| Specification |
|---|
| ECMAScript 2027 LanguageSpecification # sec-object.prototype.tostring |
This page was last modified on 22 de mai. de 2026 by MDN contributors.
ObjectObject.assign()Object.create()Object.defineProperties()Object.defineProperty()Object.entries()Object.freeze()Object.fromEntries()Object.getOwnPropertyDescriptor()Object.getOwnPropertyDescriptors()Object.getOwnPropertyNames()Object.getOwnPropertySymbols()Object.getPrototypeOf()groupBy()Object.hasOwn()Object.is()Object.isExtensible()Object.isFrozen()Object.isSealed()Object.keys()Object.preventExtensions()Object.seal()Object.setPrototypeOf()Object.values()Object.prototype.__defineGetter__()Object.prototype.__defineSetter__()Object.prototype.__lookupGetter__()Object.prototype.__lookupSetter__()Object.prototype.hasOwnProperty()Object.prototype.isPrototypeOf()Object.prototype.propertyIsEnumerable()Object.prototype.toLocaleString()Object.prototype.toString()Object.prototype.valueOf()Object/FunctionObject.prototype.__defineGetter__()Object.prototype.__defineSetter__()Object.prototype.__lookupGetter__()Object.prototype.__lookupSetter__()Object.prototype.hasOwnProperty()Object.prototype.isPrototypeOf()Object.prototype.propertyIsEnumerable()Object.prototype.toLocaleString()Object.prototype.toString()Object.prototype.valueOf()Your blueprint for a better internet.
Portions of this content are 19982026 by individual mozilla.org contributors. Content available under a Creative Commons license.
| Web Proxy Viewer | New URL | Original Page |