Hello, your question is really kind of without context, but I think I understand what point you want to reach.
The methods .toString()
and .valueOf()
are special functions that are implicitly called when you use some specific expressions, such as direct conversion to String or Number.
How do you want to know how to use them, so we’ll have to deal with the construction of the object in question.
Example using .toString()
:
// construtor da "classe" Pessoa
function Pessoa(nome){
this.nome = nome;
this.toString = function(){
return this.nome;
};
}
var eu = new Pessoa('William');
console.log('Olá, meu nome é '+eu);
// Imprime "Olá, meu nome é William"
console.log(String(eu));
// Imprime "William"
In the case of the method .valueOf()
, it explicitly references the value you define, such as your own example, a number:
// construtor de um número "especial"
function NumeroEspecial(num){
this.num = num;
this.valueOf = function(){
return this.num;
};
}
var num = new NumeroEspecial(5);
console.log(num + 1);
// Imprime 6
console.log(Number(num));
// Imprime 5
This is an explanation only for you know the initial process, there are other factors to consider before using these types of special methods.
Well, I hope I helped!