K
K
Kerrik Sun2021-06-13 17:59:46
JavaScript
Kerrik Sun, 2021-06-13 17:59:46

How are objects converted in the toString method?

How does converting an object to a string work in this case? And, more importantly... What does a "default" method do here toString (by "default" I mean a method that has not been manually overridden in the object itself) ?

let a = {
    valueOf: function () {
        return {};
    },
    toString: function() {
        //conversion to string
    }
};

console.log(String(a)); //[object Object]

As far as I understand, the object is converted to a string directly in the toString. Because it cannot return an object and only String(a)convert that object to a string type. Because then the method toStringwill return an object, which is not very good. a method returning a non-primitive data type will be ignored.

As for the method valueOf, I think that in all those cases where its behavior has not been overridden, the object itself will be returned. And this method, as a consequence, will almost always be ignored. Simply put, I want to say that the "default" method valueOfalways returns objects.

  1. So my first question is: Does the conversion to string type happen right in the method toString? If so, does the method always toStringconvert objects to a string type?

  2. And the second question: Does the "default" method always valueOfreturn objects?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
gian_tiaga, 2021-06-14
@gian_tiaga

There are answers to your questions here
https://learn.javascript.ru/object-conversion
https://learn.javascript.ru/prototype

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question