JavaScript: Object.prototype.valueOf
obj.valueOf ()
Convert obj to a object type, return it.
[see this Binding]
For example, in obj.valueOf ()
, if type of obj is type object, returns obj itself.
[see Value Types]
It's usually called in this form:
Object.prototype.valueOf.call(arg)
The purpose is to convert a primitive value arg to a object version of arg.
[see Function Call, Apply, Bind]
It has similar behavior as Object(arg)
, except in the Object(arg)
case, if arg is null
or undefined
, it creates a empty object, while in the valueOf()
case, it throws TypeError.
[see Object Constructor]
[see Primitive Value]
Here is a table showing the conversion:
Value | Result |
---|---|
undefined | throw TypeError |
null | throw TypeError |
boolean | boolean object |
number | number object |
string | string object |
symbol | symbol object |
object | object |
const obj = {}; console.log( obj.valueOf() === obj ); // true const x1 = Object.prototype.valueOf.call ( true ); console.log( x1 ); // [Boolean: true] console.log( typeof x1 === "object" ); // true const x2 = Object.prototype.valueOf.call ( 3 ); console.log( x2 ); // [Number: 3] console.log( typeof x2 === "object" ); // true const x3 = Object.prototype.valueOf.call ( "abc" ); console.log( x3 ); // [String: 'abc'] console.log( typeof x3 === "object" ); // true
Error example:
console.log( Object.prototype.valueOf.call ( null ) ); // TypeError: Cannot convert undefined or null to object