How can I feature-detect ES6 generators?

前端 未结 2 569
小鲜肉
小鲜肉 2021-02-13 17:29

I\'m really enjoying ES6 generators. Is there a way I can detect generator support in browsers? I know generators might not be in a lot of browsers (or possible no browsers at a

相关标签:
2条回答
  • 2021-02-13 17:57

    Jeremy nicely explained how to test for generators support. You need to use eval:

    isGeneratorSupported = function(){
        try {
           eval("(function*(){})()");
           return true;
        } catch(err){
           return false;
        }
    }
    alert( isGeneratorSupported() );
    

    I will try to explain why your way does not work.

    When you check whether some of JS/html5 features are supported and you use something like this:

    function isCanvasSupported(){
      var elem = document.createElement('canvas');
      return !!(elem.getContext && elem.getContext('2d'));
    }
    

    JS engine parses you code, run it if it properly parsed and then compare the output to what you have expected and only because of this you function can tell that your feature is supported.

    When you write the code like function *(){} JS engine fail on the very first step (parsing your code) and do not even try to execute it. This happens because * is not a new function, it is a new language construct and older versions of JS engine will just throw a syntaxError. The same way if you will write function f(x, ...y) {}, function f(x, y=1){} or even just ]. They all are invalid constructs in current JS (but 2 of them are valid in ES6, and who knows maybe ] will be valid in some ES10.)

    The way to bypass it is ask your engine to somehow try to execute it. And by putting your code inside eval() you can do this.

    0 讨论(0)
  • 2021-02-13 17:58

    One of the few times that eval is actually the right solution.

    For language construct changes, you need something like this:

    try {
      eval("(function *(){})");
    } catch(err) {
      console.log(err);
      console.log("No generators");
    }
    
    0 讨论(0)
提交回复
热议问题