JS: Object.prototype.valueOf
Object.prototype.valueOf
-
returns this Binding it receives.
e.g.
myObj.valueOf() === myObj
If Type of this Binding is not a object type, either return a error, or convert it to a object type, return it.
It has similar behavior as the Object Constructor
Object(arg)
, except in theObject(arg)
case, if arg isnull
orundefined
, 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 true
orfalse
boolean object number number object string string object symbol symbol object object object const jj = {}; console.log(jj.valueOf() === jj);
// testing use of Object.prototype.valueOf // but with a primitive value as argument const x1 = Reflect.apply(Object.prototype.valueOf, true, []); console.log(typeof x1 === "object"); console.log(Boolean(x1) === true); const x2 = Reflect.apply(Object.prototype.valueOf, 3, []); console.log(typeof x2 === "object"); console.log(Number(x2) === 3); const x3 = Reflect.apply(Object.prototype.valueOf, "abc", []); console.log(typeof x3 === "object"); console.log(String(x3) === "abc");
// Error example // console.log(Object.prototype.valueOf.call(null)); // TypeError: Cannot convert undefined or null to object