Reputation: 85573
I could not understand the following:
3 * { valueOf: function(){ return 5} }
//outputs 15
When I try to use like this:
3 * { 5 }
//syntax-error
3 * {valueOf: 5}
//outputs NaN
So, how exactly is this working with {}
?
Upvotes: 1
Views: 43
Reputation: 48317
The difference is between valueOf
being a function that returns a number, or simply being a number. The valueOf
method must be a function on the object, so the numeric version isn't used.
The spec talks about how valueOf
is supposed to work in section 8.12.8, stating that it must be callable to be considered while attempting to convert the object:
- Let valueOf be the result of calling the [[Get]] internal method of object O with argument "valueOf".
- If IsCallable(valueOf) is true then,
- Let val be the result of calling the [[Call]] internal method of valueOf, with O as the this value and an empty argument list.
- If val is a primitive value, return val.
This does not seem to have any case where x.valueOf
is not callable, which is why your {valueOf: 5}
example doesn't work.
Your first case (3 * { 5 }
) is a syntax error, but even if you had a valid object on the right side, wouldn't work as section 11.5 of the spec attempts to convert the right operand to a number, unless you define a valueOf
method which returns something that can be converted.
Note that 3 * { valueOf: function(){ return "5"} }
works just fine, as "5"
can be run through toNumber
just fine (following normal coercion rules).
Upvotes: 5
Reputation: 5742
valueOf
is a special attribute on objects. When an object has a valueOf
attribute that is a function, that function is called to get the literal value of the object.
In your example, you are making valueOf
a literal of 5, which is not a function that can be called by javascript
Upvotes: 0