[[DefaultValue]] - When Is toString Not an Object?

# Garrett Smith (17 years ago)

The question I have is about the internal [[DefaultValue]] function.

When [[DefaultValue]] is called with hint String, it first looks for a toString method. This seems strange because every native object would have a toString method in the prototype chain.

To get the [DefaultValue] to call O's valueOf, it is necessary to shadow any toString method with a primitive value.

({"0" : 12}) [{toString:1,valueOf:function(){return "0";}}]

Results Firefox 3, Webkit: 12 Opera 9.5 Error

Why is it this way?

==================================================== When the [[DefaultValue]] method of O is called with hint String, the following steps are taken:

  1. Call the [[Get]] method of object O with argument "toString".
  2. If Result(1) is not an object, go to step 5.
  3. Call the [[Call]] method of Result(1), with O as the this value and an empty argument list.
  4. If Result(3) is a primitive value, return Result(3).
  5. Call the [[Get]] method of object O with argument "valueOf".
  6. If Result(5) is not an object, go to step 9. 7. Call the [[Call]] method of Result(5), with O as the this value and an empty argument list.
  7. If Result(7) is a primitive value, return Result(7).
  8. Throw a TypeError exception. ====================================================