Please explain what exactly happens in the following example:

var user = { firstName: 'Alex', toString: function() { return 'User: ' + this.firstName; } }; 

As far as I understand it, this is correlated with user.toString (), although in addition to the above example, the method is “modified”. Does the function returned by the method change its prototype of behavior or how to correctly understand it. Please correct me and indicate the true path (: D) in the places where I made a mistake.

    2 answers 2

    The toString() method is automatically called on objects when they need to be cast to a string type. For example, the following lines are equivalent, just in the first cast occurs implicitly:

     1 + "" // => "1" (1).toString() // => "1" 

    So, for your own objects, you may want to define your own casting logic to a string type. If you take a user object from your snippet and try to bring it to a string type, you get the following:

     user.toString() // => "User: Alex" user + '' // => "User: Alex" 
    • Thank you very much for the answer, it became much clearer :) - Adrian

    In this code, the toString method is defined, which will be called when casting an object to a string:

     var user1 = { firstName: 'Alex', }; document.write("<div>Значение без метода toString: ", user1, "</div>"); var user2 = { firstName: 'Alex', toString: function() { return 'User: ' + this.firstName; } }; document.write("<div>Значение с методом toString: ", user2, "</div>"); 

    • @KolesnichenkoDS, a typo in the line and an error in the code - a little different things :) - Grundy
    • Thanks for the clarification, the answer from KolesnichenkoDS, in addition to your detailed example with the results obtained, helped me to understand this point more - Adrian