JS: Object .prototype .valueOf
Object.prototype.valueOf
Object.prototype.valueOf-
return the value of this (binding) it receives. e.g.
myObj.valueOf() === myObjIf type of this (binding) is not an object type, either throw an error, or convert it to an object type, return it.
It has similar behavior as the Object Constructor
Object(arg), except in theObject(arg)case, if arg isnullorundefined, it creates a empty object, while in thevalueOf()case, it throws TypeError.It's usually called in one of the following form:
Object.prototype.valueOf.call(x)Reflect.apply(Object.prototype.valueOf, x, [])
[see Function Call, Apply, Bind]
Here is a table showing the conversion:
Value Result undefined throw TypeError null throw TypeError trueorfalseboolean object number number object string string object symbol symbol object object object const jj = {}; console.assert(jj.valueOf() === jj);
Edge case. on primitive
// testing use of Object.prototype.valueOf but with a primitive value as argument console.assert( typeof Reflect.apply( Object.prototype.valueOf, true, [], ) === "object", ); console.assert( typeof Reflect.apply( Object.prototype.valueOf, 3, [], ) === "object", ); console.assert( typeof Reflect.apply( Object.prototype.valueOf, "abc", [], ) === "object", );
Edge cases. on null
// Object.prototype.valueOf on null try { Reflect.apply(Object.prototype.valueOf, null, []); } catch (xerror) { console.log(xerror); } // TypeError: Cannot convert undefined or null to object