O método JavaScript Object toString () retorna o objeto como uma string.
A sintaxe do toString()
método é:
obj.toString()
Aqui obj
está um objeto.
Parâmetros toString ()
O toString()
método não leva nenhum parâmetro.
Valor de retorno de toString ()
- Retorna uma string que representa o objeto.
Nota : Cada objeto descendente de Object
herda toString()
e se não for substituído, ele retorna "(object )"
.
Exemplo: usando toString ()
// built-in objects let num = 10; // number takes in optional radix argument (numeral base) console.log(num.toString(2)); // "1010" in binary console.log(new Date().toString()); // Thu Aug 06 2020 12:08:44 GMT+0545 (Nepal Time) // overriding default toString(), custom object function Dog(name, breed, sex) ( this.name = name; this.breed = breed; this.sex = sex; ) dog1 = new Dog("Daniel", "bulldog", "male"); console.log(dog1.toString()); // (object Object) Dog.prototype.toString = function dogToString() ( return `$(this.name) is a $(this.sex) $(this.breed).`; ); console.log(dog1.toString()); // Daniel is a male bulldog.
Resultado
1010 Qui 06 de agosto de 2020 12:08:44 GMT + 0545 (Hora do Nepal) (objeto do objeto) Daniel é um buldogue macho.
Leitura recomendada: objeto JavaScript valueOf ()