简体   繁体   中英

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

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 A { }) instanceof Function , but typeof (class A { }) == "function" ? Why not object ?

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

class es are just syntactic sugar for constructor functions. Ie the evaluation of class A {} produces a function.

The following two examples are (more or less) equivalent, ie 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.

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