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 ?
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 );
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.