Difference between Object.getPrototypeOf (x) and x.constructor.prototype?

For most x values ​​that I tested, the following value is true :

 Object.getPrototypeOf(x) === x.constructor.prototype 

... but there are a few exceptions: if x is a string, the LHS expressions above with an error, for example

 TypeError: "abc" is not an object 

... although, for example, "abc".constructor.prototype evaluates to String.prototype . Similar results are obtained if x is a number or a boolean.

What's happening? Are there any other exceptions for the identity shown earlier?

Moreover, the above suggests that x.constructor.prototype more reliable than Object.getPrototypeOf(x) .

Is there a good reason not to use x.constructor.prototype to forget about Object.getPrototypeOf(x) exclusively and completely?

+4
source share
2 answers

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.

+1
source

Object.getPrototypeOf is not supported by older browsers, where x.constructor.prototype is a more cross-browser solution.

However, if available, it is more reliable to use Object.getPrototypeOf, because x.constructor can be changed as follows: x.constructor = 'my new value';

I suggest you create this polyfill function:

 if (!Object.getPrototypeOf) { Object.getPrototypeOf = function(o) { return o.__proto__ || o.constructor.prototype; }; } 
0
source

Source: https://habr.com/ru/post/1500215/


All Articles