简体   繁体   中英

why {}__proto__ instanceof !== Object

This just does not make sense to me, please someone, explain the last line of it:

var o = {};
o.__proto__.isPrototypeOf(Object)  // true
o.__proto__.constructor.name       // 'Object'
o.__proto__.toString()             // '[object Object]'
o.__proto__ instanceof Object      // false (wtf???)

Let me rephrase my original question - I am not looking for understanding HOW IT WORKS INTERNALLY BUT WHY IT WORKS THIS WAY (although sometimes it helps) - I mean : why JS engine constructs dunder proto ( __proto__ ) AS an object which is not instance of Object EVEN if it has 'constructor' set AND even if ALL object literals ARE instances of Object (eg. o instanceof Object === true , ({}) instanceof Object === true ).

In other words - instanceof of WHAT is dunder proto when dunder proto is not manually constructed ?

And why it has 'constructor' property set if "it's not an instance" as somebody wrote? According to MDN : "All objects inherit a constructor property from their prototype" - if dunder proto object has constructor property it should mean it was inherited from 'some' prototype... So, it would make sense to me if 'constructor' property was NOT SET for 'root' dunder proto

(I did not use dunder proto as it was discouraged but yesterday I read it's official part of ES6 so I took a look at it)

instanceof does a bit of book-keeping, and then executes the HasInstance "method".

HasInstance is defined as:

Returns a Boolean value indicating whether the argument is likely an Object that was constructed by this object.

Since your object's prototype wasn't constructed, it must always return false when using instanceof . In contrast,

o instanceof Object

returns true, because o is an instance.

How does this actually work? Well, HasInstance goes through the whole prototype chain of the object it is inspecting. But o.__proto__ doesn't have a prototype - so it's not considered an object, and HasInstance returns false.

If you're used to dealing with class-based OOP languages, Javascript's OOP(/FP :P) can be quite a challenge. I'd refer you to some article that explains this well, but sadly, I haven't found any so far - and reading the specification is likely to make you even more confused (it's not one of the better specifications out there).

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