Why in JavaScript class A instanceof Function, but typeof class A is not an object?

前端 未结 1 1227
有刺的猬
有刺的猬 2021-01-25 05:17

When we say \"instance of\", we assume that we are dealing with an object. Why JavaScript\'s operator instanceof returns true when we ask (class

相关标签:
1条回答
  • 2021-01-25 05:44

    Why JavaScript's operator instanceof returns true when we ask (class A { }) instanceof Function

    classes are just syntactic sugar for constructor functions. I.e. the evaluation of class A {} produces a function.

    The following two examples are (more or less) equivalent, i.e. they produce the same result/value:

    // class
    class A {
      constructor() {
        this.foo = 42;
      }
    
      bar() {
        console.log(this.foo);
      }
    }
    
    // constructor function
    function A() {
      this.foo = 42;
    }
    
    A.prototype.bar = function() {
      console.log(this.foo);
    }
    

    Everything that is not a primitive value (string, number, boolean, null, undefined, symbol) is an object in JavaScript. Functions are objects too, with special internal properties that makes them callable (and/or constructable).


    Why not object?

    typeof returns the string "function" for function values because that's how it is defined in the specification.

    0 讨论(0)
提交回复
热议问题