El método JavaScript Object toString () devuelve el objeto como una cadena.
La sintaxis del toString()
método es:
obj.toString()
Aquí obj
hay un objeto.
Parámetros de toString ()
El toString()
método no toma ningún parámetro.
Valor de retorno de toString ()
- Devuelve una cadena que representa el objeto.
Nota : Todos los objetos que descienden de Object
heredan toString()
y, si no se anulan, regresan "(object )"
.
Ejemplo: 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.
Salida
1010 Thu Aug 06 2020 12:08:44 GMT + 0545 (hora de Nepal) (objeto Objeto) Daniel es un bulldog macho.
Lectura recomendada: JavaScript Object valueOf ()