How can I feature-detect ES6 generators?

我与影子孤独终老i 提交于 2019-12-03 10:59:11
Jeremy J Starcher

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");
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!