Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
83
rated 0 times [  84] [ 1]  / answers: 1 / hits: 59524  / 14 Years ago, fri, october 15, 2010, 12:00:00

Javascript has lot's of tricks around types and type conversions so I'm wondering if these 2 methods are the same or if there is some corner case that makes them different?


More From » javascript

 Answers
6

They are not completely the same, and actually, the String constructor called as a function (your first example), will at the end, call the toString method of the object passed, for example:



var o = { toString: function () { return foo; } };
String(o); // foo


On the other hand, if an identifier refers to null or undefined, you can't use the toString method, it will give you a TypeError exception:



var value = null;
String(null); // null
value.toString(); // TypeError


The String constructor called as a function would be roughly equivalent to:



value + '';


The type conversion rules from Object-to-Primitive are detailed described on the specification, the [[DefaultValue]] internal operation.



Briefly summarized, when converting from Object-to-String, the following steps are taken:




  1. If available, execute the toString method.


    • If the result is a primitive, return result, else go to Step 2.


  2. If available, execute the valueOf method.


    • If the result is a primitive, return result, else go to Step 3.


  3. Throw TypeError.



Given the above rules, we can make an example of the semantics involved:



var o = {
toString: function () { return foo; },
valueOf: function () { return bar; }
};

String(o); // foo

// Make the toString method unavailable:
o.toString = null;

String(o); // bar

// Also make the valueOf method unavailable:
o.valueOf = null;

try {
String(o);
} catch (e) {
alert(e); // TypeError
}


If you want to know more about this mechanism I would recommend looking at the ToPrimitive and the ToString internal operations.



I also recommend reading this article:




[#95300] Thursday, October 14, 2010, 14 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
alorac

Total Points: 262
Total Questions: 82
Total Answers: 97

Location: Libya
Member since Mon, Dec 7, 2020
4 Years ago
alorac questions
Sat, Oct 10, 20, 00:00, 4 Years ago
Tue, Sep 22, 20, 00:00, 4 Years ago
Wed, Jul 1, 20, 00:00, 4 Years ago
Wed, Jun 3, 20, 00:00, 4 Years ago
Sun, May 17, 20, 00:00, 4 Years ago
;