Why does adding a string to Date call toString () and not valueOf ()?

Just stumbled upon this today and I couldn't find where this behavior is defined in the spec.

Adding a string to an object in JavaScript (i.e. new Object() + "whatever"

) usually causes an object call valueOf()

for the object, but Date objects seem to be the exception to this rule: new Date() + "..."

calls toString()

on instead.

function test(constructor)
{
    var name = constructor.name || /^\s*function ([\w\$]+)/.exec(constructor.toString())[1];
    var obj = new constructor();
    obj.toString = function () { return name + ' : toString()'; }
    obj.valueOf = function () { return 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);
      

Run codeHide result


The question is: what is happening here with Date objects?

+3


source to share


1 answer


When you call the add statement of an object and the object is converted to a primitive , [[DefaultValue]]

the
object's internal method is called . The method takes prompt type which determines whether the estimate must first toString

or valueOf

.

If the hint is "String", then toString

look up, up valueOf

. If "Number" is transmitted, it is the other way around.

However (my attention):



When the inner method [[DefaultValue]]

O is called without a hint, it behaves as if the hint was a Number, unless O is a Date object (see 15.9.6 ), in which case it behaves as if the hint was a string .

This is also noted in the statement section:

NOTE 1 In steps 5 and 6. ToPrimitive

not specified in calls . All original ECMAScript objects other than Date objects handle hint absence as if a hint number had been specified; Date objects handle the absence of a hint as if a hint string were supplied. Host objects can handle missing hints in some other way.

+4


source







All Articles