如何使用新浏览器中可用的扩展 JS 语法 [英] How to use extended JS syntax available in new browsers

查看:27
本文介绍了如何使用新浏览器中可用的扩展 JS 语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想编写一个 JavaScript 函数,它在浏览器支持时使用新语法(bigint 文字 42n):

 

但是文档 说:><块引用>

注意:不推荐使用Function构造函数来创建函数,因为它需要函数体作为字符串,这可能会阻止一些JS引擎优化,也可能导致其他问题.

我的功能是 CPU 密集型的,所以我不希望由于缺乏一些 JS 引擎优化"而导致性能损失.
我需要一些解决方法.
我可以将脚本分成两部分(第一个在旧浏览器上会失败),但我怀疑这是最好的方法:

 <script type="text/javascript">if (!window.FortyTwo) FortyTwo = function () {return 42;};

包含使用新 JS 语法的脚本的首选方法是什么?

解决方案

您可以使用 webpack<自动转换所有代码/a>、babel跨浏览器.有一些设置开销,但您可以像这样编写所有代码:

alert(42n + 22n)//64

您可以通过这种方法获得大部分可用的新语法,甚至是尚未准备好发布的语法.

<小时>

另一个选项 - 使用 polyfill

<script src="https://cdnjs.cloudflare.com/ajax/libs/big-integer/1.6.48/BigInteger.js"></script>

然后像这样编写所有代码

alert(BigInt(42) + BigInt(2))//44

I want to write a JavaScript function which uses new syntax (bigint literal 42n) when browser supports it:

  <script type="text/javascript">
     if (window.BigInt)
        FortyTwo = Function('return 42n;');
     else
        FortyTwo = function () {return 42;};
  </script>

But the documentation says:

Note: Using the Function constructor to create functions is not recommended since it needs the function body as a string which may prevent some JS engine optimizations and can also cause other problems.

My function is CPU-intensive, so I don't want performance loss due to lack of "some JS engine optimizations".
I need some workaround.
I can split the script in two (the first one will fail on old browsers), but I doubt this is the best way:

  <script type="text/javascript">
     FortyTwo = function () {return 42n;};
  </script>
  <script type="text/javascript">
     if (!window.FortyTwo) FortyTwo = function () {return 42;};
  </script>

What is the preferred way to include a script which uses new JS syntax?

解决方案

You can convert all your code automatically using webpack, babel and cross-browser. There is some setup overhead but you can write all your code like this:

alert(42n + 22n) // 64

You get most of the new syntax available with this approach, and even syntax that's not yet ready for release.


The other option - use a polyfill

<script src="https://cdnjs.cloudflare.com/ajax/libs/big-integer/1.6.48/BigInteger.js"></script>

then write all your code like this

alert(BigInt(42) + BigInt(2)) // 44

这篇关于如何使用新浏览器中可用的扩展 JS 语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆