什么是“使用严格”用JavaScript做什么,背后的原因是什么? [英] What does "use strict" do in JavaScript, and what is the reasoning behind it?

查看:163
本文介绍了什么是“使用严格”用JavaScript做什么,背后的原因是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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


第1行问题1:缺少使用严格声明。

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?

推荐答案

这篇关于Javascript Strict Mode的文章可能会让您感兴趣: John Resig - 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:


  • 它捕获了一些常见的编码bloopers,抛出例外。

  • 当采取相对不安全的操作时(例如获取对全局对象的访问权限),它会阻止或抛出错误。

  • 它会禁用令人困惑或经过深思熟虑的功能。

另请注意,您可以应用严格模式 到整个文件......或者你只能将它用于特定的函数(仍引用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 ;-)

所以,我认为它有点像您可以在Perl 中使用use strict(因此名称?):通过检测可能导致破坏的更多内容,它可以帮助您减少错误。

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.

目前,所有主流浏览器都支持 (IE 9及以下版本)

Currently, it's supported by all major browsers (bar IE 9 and below).

这篇关于什么是“使用严格”用JavaScript做什么,背后的原因是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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