"use strict" 是什么意思?在 JavaScript 中做,背后的原因是什么? [英] What does "use strict" do in JavaScript, and what is the reasoning behind it?

查看:38
本文介绍了"use strict" 是什么意思?在 JavaScript 中做,背后的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

最近,我通过 Crockford 的 JSLint 运行了一些 JavaScript 代码,但出现以下错误:

Recently, I ran some of my JavaScript code through Crockford's JSLint, and it gave the following error:

第 1 行字符 1 的问题:缺少use strict"语句.

Problem at line 1 character 1: Missing "use strict" statement.

通过一些搜索,我发现有些人将 "use strict"; 添加到他们的 JavaScript 代码中.添加语句后,错误不再出现.不幸的是,谷歌没有透露这个字符串语句背后的大部分历史.当然,这肯定与浏览器如何解释 JavaScript 有关系,但我不知道会产生什么效果.

Doing some searching, I realized that some people add "use strict"; into their JavaScript code. Once I added the statement, the error stopped appearing. Unfortunately, Google did not reveal much of the history behind this string statement. Certainly it must have something to do with how the JavaScript is interpreted by the browser, but I have no idea what the effect would be.

那么 "use strict"; 到底是什么,它意味着什么,它仍然相关吗?

So what is "use strict"; all about, what does it imply, and is it still relevant?

当前的浏览器是否对 "use strict"; 字符串做出响应,或者是否供将来使用?

Do any of the current browsers respond to the "use strict"; string or is it for future use?

推荐答案

ES6 模块更新

原生 ECMAScript 模块 内(带有 importexport 语句)和 ES6 类,严格模式始终处于启用状态,无法禁用.

Update for ES6 modules

Inside native ECMAScript modules (with import and export statements) and ES6 classes, strict mode is always enabled and cannot be disabled.

这篇关于 Javascript 严格模式的文章可能会让您感兴趣:JohnResig - ECMAScript 5 严格模式、JSON 等

This article about Javascript Strict Mode might interest you: John Resig - ECMAScript 5 Strict Mode, JSON, and More

引用一些有趣的部分:

严格模式是 ECMAScript 5 中的一项新功能,它允许您将程序或函数置于严格"模式中.操作上下文.这种严格的上下文会阻止执行某些操作并引发更多异常.

Strict Mode is a new feature in ECMAScript 5 that allows you to place a program, or a function, in a "strict" operating context. This strict context prevents certain actions from being taken and throws more exceptions.

还有:

严格模式有以下几个方面的帮助:

Strict mode helps out in a couple ways:

  • 它会捕获一些常见的编码错误,引发异常.
  • 当相对不安全"时,它会阻止或抛出错误采取行动(例如获得对全局对象的访问权限).
  • 它会禁用令人困惑或深思熟虑的功能.

另请注意,您可以应用严格模式";到整个文件...或者您可以仅将其用于特定功能(仍然引用 John Resig 的文章):

Also note you can apply "strict mode" to the whole file... Or you can use it only for a specific function (still quoting from John Resig's article):

// Non-strict code...

(function(){
  "use strict";

  // Define your library strictly...
})();

// Non-strict code...

如果您必须混合旧代码和新代码,这可能会有所帮助;-)

Which might be helpful if you have to mix old and new code ;-)

所以,我想这有点像 use strict" 您可以在 Perl 中使用 (因此得名?):它通过检测更多可能导致损坏的内容来帮助您减少错误.

So, I suppose it's a bit like the "use strict" you can use in Perl (hence the name?): it helps you make fewer errors, by detecting more things that could lead to breakages.

严格模式现在所有主要浏览器都支持.

这篇关于"use strict" 是什么意思?在 JavaScript 中做,背后的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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