如何使用新浏览器中可用的扩展 JS 语法

编程入门 行业动态 更新时间:2024-10-18 06:09:55
本文介绍了如何使用新浏览器中可用的扩展 JS 语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时送ChatGPT账号..

我想编写一个 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/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/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屋!

更多推荐

[db:关键词]

本文发布于:2023-05-01 13:16:57,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1410119.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何使用   语法   器中   JS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!