I am wondering what is the difference between Array.prototype.isPrototypeOf
and Array.isPrototypeOf
I thought it should work the same because I thought it will refer to the same method isPrototypeOf
but It's look like I was mistaken. Can anybody explain to me why this work like that ?
const exampleArray = [1, 2, 3]; console.log(Array.prototype.isPrototypeOf(exampleArray)); console.log(Array.isPrototypeOf(exampleArray)); // Why this statement returns false ?
The JavaScript array prototype constructor is used to allow to add new methods and properties to the Array() object. If the method is constructed, then it will available for every array. When constructing a property, All arrays will be given the property, and its value, as default. Syntax: Array.prototype.name = value.
isPrototypeOf() The isPrototypeOf() method checks if an object exists in another object's prototype chain.
In the specs, the reason is said to be: The Function prototype object is specified to be a function object to ensure compatibility with ECMAScript code that was created prior to the ECMAScript 2015 specification. (this also applies to arrays) That's the why.
The prototype of an object is referred to by the prototype property of the constructor function that creates and initializes the object. The isPrototypeOf() method provides a way to determine if one object is the prototype of another. This technique can be used to determine the class of an object.
Those are both references to Object.prototype.isPrototypeOf()
, which checks to see if the object it's called on is in the prototype chain of the passed argument.
For the exampleArray
, the prototype chain is this:
Object.prototype <- Array.prototype <- exampleArray instance
See snippet:
const exampleArray = [1, 2, 3]; console.log( Object.getPrototypeOf(exampleArray) === Array.prototype, Object.getPrototypeOf(Array.prototype) === Object.prototype );
The Array constructor function - window.Array
- is not in the prototype chain, so isPrototypeOf
returns false
.
The Array constructor function would only have isPrototypeOf
return true
if a class extended Array
, or if it was set to be the internal prototype of a new object via Object.create
, eg:
class ExtendedArray extends Array {} console.log(Array.isPrototypeOf(ExtendedArray)); const somethingWeird = Object.create(Array); console.log(Array.isPrototypeOf(somethingWeird));
For completeness, the Array constructor function - being a function - inherits from Function.prototype
, which inherits from Object.prototype
:
console.log( Object.getPrototypeOf(Array) === Function.prototype, Object.getPrototypeOf(Function.prototype) === Object.prototype );
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With