为什么不应该在JavaScript中使用eval()的原因

The eval() function has been around for a long time in JavaScript! You likely don’t see it often anymore because it’s widely agreed that it’s harmful to use. Let’s take a brief look at it, and some of the dangers associated with using it.

eval()函数在JavaScript中已经存在很长时间了! 您可能不会再经常看到它了,因为人们普遍认为它使用有害。 让我们简要地看一下它,以及与使用它相关的一些危险。

The keyword eval is an abbreviation for “evaluate.” The function essentially takes a string with JavaScript code and will evaluate it for you.

关键字eval是“评估”的缩写。 该函数本质上采用带有JavaScript代码的字符串,并将为您评估它。

eval('2 + 3 + 1');
// 6

You can evaluate a simple expression… Or a bunch of JavaScript code!

您可以评估一个简单的表达式…或一堆JavaScript代码!

var foo = 2;

eval('var bar = 3;\
var baz = 1;\
\
function addStuff() {\
  return foo + bar + baz;\
}\
\
addStuff();\
');
// 6

避免使用eval()原因 (Reasons to Avoid Using   eval())

Unless you are doing really high-level JavaScript (see below) the risks usually outweigh the benefits of using eval(). Here’s some of the reasons to avoid using it:

除非您使用的是真正的高级JavaScript(请参阅下文),否则风险通常会超过使用eval()的好处。 以下是避免使用它的一些原因:

  • Malicious code: invoking eval can crash a computer. For example: if you use eval server-side and a mischievous user decides to use an infinite loop as their username.

    恶意代码 :调用eval可能会使计算机崩溃。 例如:如果您使用eval服务器端,并且顽皮的用户决定使用无限循环作为其用户名。

  • Terribly slow: the JavaScript language is designed to use the full gamut of JavaScript types (numbers, functions, objects, etc)… Not just strings! Using eval is orders of magnitude slower than normal JavaScript code.

    非常慢 :JavaScript语言被设计为使用全部JavaScript类型(数字,函数,对象等)…不仅仅是字符串! 使用eval比普通JavaScript代码慢eval数量级。

Considering that eval() is still part of the ECMAScript standard… Are there any appropriate uses for it?

考虑到eval()仍然是ECMAScript标准的一部分...是否有适当的用途?

eval()合法用途 (Legitimate Uses for   eval())

There’s a small subset of JavaScript development that requires using eval. These include: developing template libraries, interpreters, command lines and module systems. Most of these types of software development are meta-programming and build tools.

JavaScript开发的一小部分需要使用eval 。 其中包括:开发模板库,解释器,命令行和模块系统。 这些类型的软件开发大多数是元编程和构建工具。



If you’re unsure whether to use eval, try doing a quick search on StackOverflow. There’s almost always a better approach.

如果不确定是否使用eval ,请尝试在StackOverflow上进行快速搜索。 几乎总是有更好的方法。

翻译自: https://www.digitalocean.com/community/tutorials/js-eval

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值