Strings (and other primitives) can behave a bit strange.
Basically, when you try to access a property of a primitive, it is queued using Just-In-Time, using the equivalent of Object, and then the property of that object is returned.
So, in this case, when you try to access "abc".constructor
, what actually happens is the same as new String("abc").constructor
(which, of course, returns a String
object).
On the other hand, Object.getPrototypeOf
does not do such a box; instead, it returns an error if you pass it something that is not an object.
Do you think that x.constructor.prototype
seems to be a more reliable method for defining the constructor of something, since it handles this “boxing” case. Nevertheless, I personally can’t imagine any real situation when something like this might be needed, because ... well, as a rule, you already know what type it is. For the same reason, I don't see a real point in using ===
most of the time.
source share