简体   繁体   中英

is there a generic, explicit primitive -> object cast in JavaScript?

I have the following puzzle (works in NodeJS):

console.log((42).toFixed);
console.log(Object.getPrototypeOf(42));

While the first line does show [Function: toFixed] , the second fails with TypeError: Object.getPrototypeOf called on non-object . This, I believe, is the correct behavior as for the spec (but puzzling for anyone how believes that everything is an object in JavaScript ).

Now I would like to write a method like console.dir that outputs all the properties of an object, including those coming from prototypes, and including those that are in fact accessible from primitive values.

Of course, the crux of the matter is that JavaScript tries to be smart and does a behind-the-scenes sleight-of-hand, casting the primitive value 42 to something akin to new Number( 42 ) . The trick is done when you access a certain named property on the primitive value, but not when the value is an argument to getPrototypeOf (I believe it really should).

In order to reach my goal, I could go and determine the type of the primitive value in case getPrototypeOf should fail, and then pick from a hopefully limited number of possibilities ( Number , String , Boolean , ...) the right one. this does not even sound difficult.

But it does feel a little ... wrong. What feels much better is a built-in / custom method cast_as_object that converts a primitive to an object no matter what its type is, preferably in some generic and future-proof way. Is that possible?

(nb It's trivial to go from type name to prototype when type names are unique and the set of primitives is small and closed—but I'm asking this question with the hope that answers will help people to better understand that theoretically simple yet practically intricate beast that is JavaScript's object model).

@Ken Kin—asking for a feature is asking a question, no?—not sure what you're implying here.

@charlietfl—i believe i stated benefits in my text, to quote: "I would like to write a method like console.dir that outputs all the properties of an object". as it stands, console.dir will simply echo the stringification (what a word) of a primitive value (and, oddly, new Object( 42 ) results in {} ).

the solution turns out to be quite simple, as brought forth by @GameAlchemist: after doing

value = new Object( primitive_value )

you can apply Object.getOwnPropertyNames and Object.getPrototypeOf to value , allowing to retrieve all properties on the object and the prototype chain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM