Why in JavaScript both “Object instanceof Function” and “Function instanceof Object” return true?

前端 未结 7 1195
梦如初夏
梦如初夏 2020-11-27 03:33

Why in JavaScript do both Object instanceof Function and Function instanceof Object return true?

I tried it in Safari WebInspe

7条回答
  •  悲哀的现实
    2020-11-27 04:06

    Very Simple Explanation, Different from all answers

    Both Object and Function are constructors(type of both with return "Function objects") and both are created from Function Constructor. The __proto__ property of both these point to 'Function.prototype' object.

    QUICK EXPLANATION: __proto__ property of an object(say p1 which is Person type) points to the Constructor's protoype(say Person.prototype) Again the __proto__ in the prototype chain points to the object "Object.prototype".

    BEFORE READING FURTHER PRINT DETAILS ON CHROME CONSOLE console.dir(Object), console.dir(Function)

    KEEP IN MIND, function constructors and also objects so you will see both .prototype and __proto__ properties. In all the instance objects(say p1) you will only find the __proto__ property. The __proto__ is accessor for hidden property [[Prototye]] and best way to get is Object.getPrototypeOf(p1) as __proto__ is depricated.

    (p1 instanceof Person) here operator checks if the Constructor Person's prototype is in the prototypal chain of the object p1. take a note that first value is instance object(p1) and second value is a constructor (Person).

    Lets analyze => Function instanceof Object.

    Function object's __proto__.__proto__ points to Object.prototype , So its true

    Lets analyze => Object instanceof Function.

    Object object's __proto__ points to Function.prototype, So its true

    Hope this helps.

提交回复
热议问题