Saturday, 15 May 2010

javascript - Why does appending a string to a Date invoke toString() rather than valueOf()? -



javascript - Why does appending a string to a Date invoke toString() rather than valueOf()? -

just stumbled upon today , couldn't find behavior defined in spec.

appending string object in javascript (i.e. new object() + "whatever") typically triggers phone call valueof() on object, apparently, date objects exception rule: new date() + "..." calls tostring() on date instead.

class="snippet-code-js lang-js prettyprint-override">function test(constructor) { var name = constructor.name || /^\s*function ([\w\$]+)/.exec(constructor.tostring())[1]; var obj = new constructor(); obj.tostring = function () { homecoming name + ' : tostring()'; } obj.valueof = function () { homecoming name + ' : valueof()'; } document.body.appendchild(document.createelement('div')).textcontent = obj + ''; } test(array); test(boolean); test(date); test(function); test(number); test(object); test(regexp); test(string);

question: different date objects here?

when phone call addition operator on object, , object converted to primitive, internal [[defaultvalue]] method of object called. method takes type hint determines whether tostring should evaluated first or valueof.

if hint "string", tostring looked for, before valueof. if "number" passed, it's vice versa.

however (emphasis mine):

when [[defaultvalue]] internal method of o called no hint, behaves if hint number, unless o date object (see 15.9.6), in case behaves if hint string.

this noted in addition operator section:

note 1 no hint provided in calls toprimitive in steps 5 , 6. native ecmascript objects except date objects handle absence of hint if hint number given; date objects handle absence of hint if hint string given. host objects may handle absence of hint in other manner.

javascript

No comments:

Post a Comment