How can I differentiate between an arrow function, class and a normal function?

前端 未结 2 565
别那么骄傲
别那么骄傲 2020-12-02 02:12

How can I differentiate between these three things in ES6 using its reference?

let x = i => i+1;

class y { constructor(i) { this._i=i+1; } get i(){ retur         


        
2条回答
  •  误落风尘
    2020-12-02 03:04

    You can't the first two cases get transpiled into this:

    var x = function x(i) {
      return i + 1;
    };
    
    function z(i) {
      return i + 1;
    }
    

    For the last one you could check if it complains if it's a class when you call it:

    function isClass(instance){
      try{
        instance()
      }catch(e){
        return e.message === "Cannot call a class as a function";
      }
      return false;
    }
    

    But that will obviously trigger the side effects of calling it, so it doesn't work in the general case.

提交回复
热议问题