Object and Function are quite confusing

前端 未结 7 1800
隐瞒了意图╮
隐瞒了意图╮ 2020-12-10 03:47
Object instanceof Object
true
Object instanceof Function
true
Function instanceof Object
true
Function instanceof Function
true

so if Function is a

7条回答
  •  不知归路
    2020-12-10 04:16

    Everything is an Object in JavaScript because JavaScript is an object-oriented language. Function is an instance of Object because everything is an instance of Object. Simple enough. However, objects that initialize other objects (constructors) are also Functions in JavaScript, so it would make sense for Object to also be a Function.

    Think about this:

    var obj = new Object();
    

    Object in this case is used as a Function, is it not? So while, in theory, Object should be the lowest-level object in the language, JavaScript cannot function without Functions (pun!), so you need both to be at the same level. Object needs to be an instance of Function because it's a constructor and it needs to create more instances of itself.

    function FooBar() {}
    

    The FooBar class above is an instance of both Object and Function, because it's both. The same logic applies to the built-in Object and Function objects; they're instances of both.

    Phew, confusing. Did that make any sense?

提交回复
热议问题