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

前端 未结 8 1912
借酒劲吻你
借酒劲吻你 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条回答
  • 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]
    }
    
    0 讨论(0)
  • 2020-12-07 19:46

    Looking at the compiled code generated by Babel, I think there is no way you can tell if a function is used as a class. Back in the time, JavaScript didn't have classes, and every constructor was just a function. Today's JavaScript class keyword don't introduce a new concept of 'classes', it's rather a syntax sugar.

    ES6 code:

    // ES6
    class A{}
    

    ES5 generated by Babel:

    // ES5
    "use strict";
    
    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
    
    var A = function A() {
        _classCallCheck(this, A);
    };
    

    Of course, if you are into coding conventions, you could parse the function (the class), and check if it's name starts with a capital letter.

    function isClass(fn) {
        return typeof fn === 'function' && /^(?:class\s+|function\s+(?:_class|_default|[A-Z]))/.test(fn);
    }
    

    EDIT:

    Browsers which already support the class keyword can use it when parsing. Otherwise, you are stuck with the capital letter one.

    EDIT:

    As balupton pointed out, Babel generates function _class() {} for anonymous classes. Improved regex based on that.

    EDIT:

    Added _default to the regex, to detect classes like export default class {}

    Warning

    BabelJS is heavily under development, and there is no guarantee they will not change the default function names in these cases. Really, you shouldn't rely on that.

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