How do you check the difference between an ECMAScript 6 class and function?

前端 未结 8 1910
借酒劲吻你
借酒劲吻你 2020-12-07 19:19

In ECMAScript 6 the typeof of classes is, according to the specification, \'function\'.

However also according to the specification you are

8条回答
  •  -上瘾入骨i
    2020-12-07 19:33

    You can use new.target to determine whether whether its instantiated by ES6 class function or function constructor

    class Person1 {
      constructor(name) {
        this.name = name;
        console.log(new.target) // => // => [Class: Person1]
      }
    }
    
    function Person2(){
      this.name='cc'
      console.log(new.target) // => [Function: Person2]
    }
    

提交回复
热议问题