最近,我通过 Crockford 的 JSLint 运行了一些 JavaScript 代码,它给出了以下错误:
第 1 行字符 1 处出现问题:缺少“use strict”语句。
经过一些搜索,我发现有些人在 JavaScript 代码中添加了 "use strict";
。添加该语句后,错误就不再出现。不幸的是,谷歌并没有透露这个字符串声明背后的太多历史。当然,这肯定与浏览器如何解释JavaScript有关,但我不知道会产生什么影响。
那么 "use strict";
到底是什么,它意味着什么,它仍然相关吗?
当前的浏览器是否响应 "use strict";
字符串或者供将来使用?
Recently, I ran some of my JavaScript code through Crockford's JSLint, and it gave the following error:
Problem at line 1 character 1: Missing "use strict" statement.
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.
So what is "use strict";
all about, what does it imply, and is it still relevant?
Do any of the current browsers respond to the "use strict";
string or is it for future use?
发布评论
评论(30)
原生 ECMAScript 模块 内的ES6 模块更新
(使用
导入
和export
语句)和 ES6 类,严格模式始终启用且无法禁用。原始答案
这篇关于 Javascript 严格模式的文章可能会让您感兴趣: John Resig - ECMAScript 5 严格模式、JSON 等
引用一些有趣的部分:
和:
另请注意,您可以将“严格模式”应用于整个文件...或者您可以仅将其用于特定函数(仍然引用 John Resig 的文章):
如果您必须这样做,这可能会有所帮助混合新旧代码;-)
所以,我想这有点像
“use strict”
你可以在 Perl 中使用(因此得名?):它通过检测更多可能导致损坏的事情来帮助你减少错误。现在所有主流浏览器都支持严格模式。
Update for ES6 modules
Inside native ECMAScript modules (with
import
andexport
statements) and ES6 classes, strict mode is always enabled and cannot be disabled.Original answer
This article about Javascript Strict Mode might interest you: John Resig - ECMAScript 5 Strict Mode, JSON, and More
To quote some interesting parts:
And:
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):
Which might be helpful if you have to mix old and new code ;-)
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.Strict mode is now supported by all major browsers.
这是 ECMAScript 5 的一项新功能。John Resig 写了 一篇不错的文章总结。
它只是您放入 JavaScript 文件中(位于文件顶部或函数内部)的字符串,如下所示:
现在将其放入代码中不会对当前浏览器造成任何问题,因为它只是一个字符串。如果您的代码违反了编译指示,将来可能会导致您的代码出现问题。例如,如果您当前有
foo = "bar"
而没有首先定义foo
,您的代码将开始失败......在我看来这是一件好事。It's a new feature of ECMAScript 5. John Resig wrote up a nice summary of it.
It's just a string you put in your JavaScript files (either at the top of your file or inside of a function) that looks like this:
Putting it in your code now shouldn't cause any problems with current browsers as it's just a string. It may cause problems with your code in the future if your code violates the pragma. For instance, if you currently have
foo = "bar"
without definingfoo
first, your code will start failing...which is a good thing in my opinion.语句
“use strict”;
指示浏览器使用严格模式,这是 JavaScript 的简化且更安全的功能集。功能列表(非详尽)
不允许全局变量。 (捕获变量名称中缺少的
var
声明和拼写错误)静默失败的赋值将在严格模式下引发错误(赋值
NaN = 5;
)尝试删除不可删除的属性将抛出错误(
删除 Object.prototype
)要求对象文字中的所有属性名称都是唯一的 (
var x = {x1: "1", x1: “2”}
)函数参数名称必须是唯一的 (
function sum (x, x) {...}
)禁止八进制语法 (
var x = 023;
一些开发人员错误地假设前面的零不会改变数字。)禁止
with
关键字eval
在严格模式下不引入新变量禁止删除普通名称(
delete x;
)禁止以任何形式绑定或分配名称
eval
和arguments
严格模式不会将
arguments
对象的属性与正式的参数。 (例如,在 function sum (a,b) { return argument[0] + b;} 中,这是有效的,因为arguments[0]
绑定到a 等)(请参阅下面的
示例
部分以了解差异)不支持
arguments.callee
>
[参考:严格模式,Mozilla 开发者网络]
示例:
The statement
"use strict";
instructs the browser to use the Strict mode, which is a reduced and safer feature set of JavaScript.List of features (non-exhaustive)
Disallows global variables. (Catches missing
var
declarations and typos in variable names)Silent failing assignments will throw error in strict mode (assigning
NaN = 5;
)Attempts to delete undeletable properties will throw (
delete Object.prototype
)Requires all property names in an object literal to be unique (
var x = {x1: "1", x1: "2"}
)Function parameter names must be unique (
function sum (x, x) {...}
)Forbids octal syntax (
var x = 023;
some devs assume wrongly that a preceding zero does nothing to change the number.)Forbids the
with
keywordeval
in strict mode does not introduce new variablesForbids deleting plain names (
delete x;
)Forbids binding or assignment of the names
eval
andarguments
in any formStrict mode does not alias properties of the
arguments
object with the formal parameters. (e.g. infunction sum (a,b) { return arguments[0] + b;}
This works becausearguments[0]
is bound toa
and so on. ) (Seeexamples
section below to understand the difference)arguments.callee
is not supported[Ref: Strict mode, Mozilla Developer Network]
Examples:
如果人们担心使用
use strict
,可能值得查看这篇文章:浏览器中的 ECMAScript 5“严格模式”支持。这是什么意思?
NovoGeek.com - Krishna 的博客
它讨论了浏览器支持,但更重要的是如何安全地处理它:
If people are worried about using
use strict
it might be worth checking out this article:ECMAScript 5 'Strict mode' support in browsers. What does this mean?
NovoGeek.com - Krishna's weblog
It talks about browser support, but more importantly how to deal with it safely:
请注意,所有努力的程序员:对现有代码应用
“use strict”
可能是危险的!这东西不是一些让人感觉良好、开心的贴纸,你可以把它贴在代码上以使其“更好”。使用“use strict”
编译指示,浏览器会突然在以前从未抛出过的随机位置抛出异常,只是因为在那个位置你正在做一些默认/宽松的JavaScript高兴地允许但严格的JavaScript厌恶的事情!您可能会在代码中很少使用的调用中隐藏严格违规行为,这些调用只会在最终运行时抛出异常 - 例如,在您的付费客户使用的生产环境中!如果您打算冒险尝试,最好将“use strict”与全面的单元测试和严格配置的 JSHint 构建任务一起应用,这将使您有信心不存在任何黑暗角落仅仅因为您打开了严格模式,您的模块就会严重爆炸。或者,嘿,这里有另一个选择:只是不要将
"use strict"
添加到任何遗留代码中,老实说,这样可能更安全。 绝对不要将“use strict”
添加到您不拥有或维护的任何模块中,例如第三方模块。我认为即使它是致命的笼中动物,
“use strict”
也可以是好东西,但你必须做得对。严格执行的最佳时机是当您的项目刚刚起步并且您从头开始时。配置JSHint/JSLint
,将所有警告和选项调到您的团队能够承受的范围内,获得一个良好的构建/测试/断言系统,例如Grunt+Karma+Chai
code>,然后才开始将所有新模块标记为“use strict”
。准备好解决许多棘手的错误和警告。如果JSHint/JSLint
产生任何违规,请将构建配置为 FAIL,以确保每个人都了解重力。当我采用
“use strict”
时,我的项目并不是一个新建项目。结果,我的 IDE 充满了红色标记,因为我的一半模块没有"use strict"
,JSHint 对此抱怨。这提醒我以后应该做什么重构。我的目标是消除红色标记,因为我缺少所有“use strict”
语句,但那是几年后的事了。A word of caution, all you hard-charging programmers: applying
"use strict"
to existing code can be hazardous! This thing is not some feel-good, happy-face sticker that you can slap on the code to make it 'better'. With the"use strict"
pragma, the browser will suddenly THROW exceptions in random places that it never threw before just because at that spot you are doing something that default/loose JavaScript happily allows but strict JavaScript abhors! You may have strictness violations hiding in seldom used calls in your code that will only throw an exception when they do eventually get run - say, in the production environment that your paying customers use!If you are going to take the plunge, it is a good idea to apply
"use strict"
alongside comprehensive unit tests and a strictly configured JSHint build task that will give you some confidence that there is no dark corner of your module that will blow up horribly just because you've turned on Strict Mode. Or, hey, here's another option: just don't add"use strict"
to any of your legacy code, it's probably safer that way, honestly. DEFINITELY DO NOT add"use strict"
to any modules you do not own or maintain, like third party modules.I think even though it is a deadly caged animal,
"use strict"
can be good stuff, but you have to do it right. The best time to go strict is when your project is greenfield and you are starting from scratch. ConfigureJSHint/JSLint
with all the warnings and options cranked up as tight as your team can stomach, get a good build/test/assert system du jour rigged likeGrunt+Karma+Chai
, and only THEN start marking all your new modules as"use strict"
. Be prepared to cure lots of niggly errors and warnings. Make sure everyone understands the gravity by configuring the build to FAIL ifJSHint/JSLint
produces any violations.My project was not a greenfield project when I adopted
"use strict"
. As a result, my IDE is full of red marks because I don't have"use strict"
on half my modules, and JSHint complains about that. It's a reminder to me about what refactoring I should do in the future. My goal is to be red mark free due to all of my missing"use strict"
statements, but that is years away now.使用
'use strict';
不会突然使您的代码变得更好。JavaScript 严格模式 是 ECMAScript 5。您可以通过在脚本/函数的顶部声明它来启用严格模式。
当 JavaScript 引擎看到这个指令时,它将开始以特殊模式解释代码。在此模式下,当检测到某些可能最终成为潜在错误的编码实践时,就会引发错误(这就是严格模式背后的原因)。
考虑这个例子:
开发人员痴迷于排列数字文字,无意中用八进制文字初始化了变量
b
。非严格模式会将其解释为值为24
(以 10 为基数)的数字文字。但是,严格模式会抛出错误。有关严格模式下专业的非详尽列表,请参阅此答案。
我应该在哪里使用
'use strict';
?在我的新 JavaScript 应用程序中:绝对!当您用代码做一些愚蠢的事情时,严格模式可以用作举报者。
在我的现有 JavaScript 代码中:可能不会!如果您现有的 JavaScript 代码包含严格模式下禁止的语句,则应用程序将会崩溃。如果您想要严格模式,您应该准备好调试和更正现有代码。这就是为什么使用
'use strict';
不会突然让你的代码变得更好。如何使用严格模式?
在脚本顶部插入
'use strict';
语句:请注意,
myscript.js
文件中的所有内容都将以严格模式进行解释。或者,在函数体顶部插入
'use strict';
语句:函数
doSomething
的词法范围中的所有内容都将以严格模式进行解释。词汇范围这个词在这里很重要。例如,如果您的严格代码调用非严格库的函数,则只有您的代码会在严格模式下执行,而不是被调用的函数。请参阅此答案以获得更好的解释。严格模式下禁止哪些事情?
我发现了 好文章 描述了严格模式下禁止的几项内容(请注意,这不是详尽的列表):
未来 JavaScript 版本的保留字
ECMAScript 5 添加了保留字列表。如果将它们用作变量或参数,严格模式将引发错误。保留字是:
进一步阅读
Using
'use strict';
does not suddenly make your code better.The JavaScript strict mode is a feature in ECMAScript 5. You can enable the strict mode by declaring this in the top of your script/function.
When a JavaScript engine sees this directive, it will start to interpret the code in a special mode. In this mode, errors are thrown up when certain coding practices that could end up being potential bugs are detected (which is the reasoning behind the strict mode).
Consider this example:
In their obsession to line up the numeric literals, the developer has inadvertently initialized variable
b
with an octal literal. Non-strict mode will interpret this as a numeric literal with value24
(in base 10). However, strict mode will throw an error.For a non-exhaustive list of specialties in strict mode, see this answer.
Where should I use
'use strict';
?In my new JavaScript application: Absolutely! Strict mode can be used as a whistleblower when you are doing something stupid with your code.
In my existing JavaScript code: Probably not! If your existing JavaScript code has statements that are prohibited in strict-mode, the application will simply break. If you want strict mode, you should be prepared to debug and correct your existing code. This is why using
'use strict';
does not suddenly make your code better.How do I use strict mode?
Insert a
'use strict';
statement on top of your script:Note that everything in the file
myscript.js
will be interpreted in strict mode.Or, insert a
'use strict';
statement on top of your function body:Everything in the lexical scope of function
doSomething
will be interpreted in strict mode. The word lexical scope is important here. For example, if your strict code calls a function of a library that is not strict, only your code is executed in strict mode, and not the called function. See this answer for a better explanation.What things are prohibited in strict mode?
I found a nice article describing several things that are prohibited in strict mode (note that this is not an exhaustive list):
Reserved words for future JavaScript versions
ECMAScript 5 adds a list of reserved words. If you use them as variables or arguments, strict mode will throw an error. The reserved words are:
Further Reading
我强烈建议每个开发人员现在就开始使用严格模式。有足够多的浏览器支持它,严格模式将合法地帮助我们避免我们甚至不知道代码中存在错误。
显然,在初始阶段会出现我们以前从未遇到过的错误。为了获得全部好处,我们需要在切换到严格模式后进行适当的测试,以确保我们捕获了所有内容。当然,我们不会只是在代码中抛出
use strict
并假设没有错误。因此,现在是时候开始使用这种非常有用的语言功能来编写更好的代码了。例如,
JSLint 是 Douglas Crockford 编写的调试器。只需粘贴您的脚本,它就会快速扫描代码中任何明显的问题和错误。
I strongly recommend every developer to start using strict mode now. There are enough browsers supporting it that strict mode will legitimately help save us from errors we didn’t even know were in your code.
Apparently, at the initial stage there will be errors we have never encountered before. To get the full benefit, we need to do proper testing after switching to strict mode to make sure we have caught everything. Definitely we don’t just throw
use strict
in our code and assume there are no errors. So the churn is that it’s time to start using this incredibly useful language feature to write better code.For example,
JSLint is a debugger written by Douglas Crockford. Simply paste in your script, and it’ll quickly scan for any noticeable issues and errors in your code.
我想提供一个更有根据的答案来补充其他答案。我希望编辑最受欢迎的答案,但失败了。我尽力使其尽可能全面和完整。
您可以参阅 MDN 文档了解更多信息。
“use strict”
ECMAScript 5 中引入的指令。指令与语句类似,但又有所不同。
use strict
不包含关键字:指令是一个简单的表达式语句,由特殊的字符串文字(单引号或双引号)组成。不实现 ECMAScript 5 的 JavaScript 引擎只能看到没有副作用的表达式语句。预计 ECMAScript 标准的未来版本将引入use
作为真正的关键字;因此,这些引述将变得过时。use strict
只能在脚本或函数的开头使用,即它必须位于所有其他(真实)语句之前。它不一定是函数脚本中的第一条指令:它前面可以是由字符串文字组成的其他语句表达式(JavaScript 实现可以将它们视为特定于实现的指令)。紧随第一个实际语句(在脚本或函数中)之后的字符串文字语句是简单的表达式语句。解释者不得将它们解释为指令,并且它们没有任何作用。use strict
指令指示以下代码(在脚本或函数中)是严格代码。当脚本包含
use strict
指令时,脚本最高级别的代码(不在函数中的代码)被视为严格代码。当函数本身以严格代码定义或函数包含
use strict
指令时,函数的内容被视为严格代码。当从严格代码调用
eval()
或包含use strict
时,传递给eval()
方法的代码被视为严格代码指令本身。ECMAScript 5的严格模式是JavaScript语言的受限子集,它消除了语言的相关缺陷,具有更严格的错误检查和更高的安全性。下面列出了严格模式和普通模式之间的区别(其中前三个尤为重要):
with
语句。Object
的变量、函数、函数参数、catch 子句参数或属性的标识符,则你会得到一个ReferenceError
。在正常模式下,标识符被隐式声明为全局变量(作为全局Object
的属性)。this
的值为undefined 在作为函数(而不是方法)调用的函数中。 (在正常模式下
this
始终指向全局Object
)。这个差异可以用来测试实现是否支持严格模式:此外,当在严格模式下使用
call()
或apply
调用函数时,this
正是第一个参数的值call()
或apply()
调用。 (在正常模式下,null
和undefined
被全局Object
替换,并且不是对象的值被转换为对象。)在严格模式下,当您尝试分配只读属性或为不可扩展对象定义新属性时,您将收到
TypeError
。 (在正常模式下,两者都会失败,并且不会出现错误消息。)在严格模式下,当将代码传递给
eval()
时,您不能在调用者的范围内声明或定义变量或函数(如你可以在正常模式下完成)。相反,会为eval()
创建一个新作用域,并且变量和函数都在该作用域内。该作用域在eval()
执行完成后被销毁。在严格模式下,函数的参数对象包含传递给该函数的值的静态副本。在正常模式下,参数对象有一个有点“神奇”的行为:数组的元素和命名函数参数引用相同的值。
在严格模式下,当
delete
运算符后跟非限定标识符(变量、函数或函数参数)时,您将收到SyntaxError
。在正常模式下,delete
表达式不会执行任何操作,并且计算结果为false
。在严格模式下,当您尝试删除不可配置的属性时,您将收到
TypeError
。 (在正常模式下,尝试会失败,delete
表达式的计算结果为false
)。在严格模式下,当您尝试为对象字面量定义多个同名属性时,会被视为语法错误。 (正常模式下没有错误。)
在严格模式下,当函数声明具有多个同名参数时,将被视为语法错误。 (正常模式下没有错误。)
在严格模式下,不允许使用八进制文字(这些是以
0
开头的文字。(在正常模式下,某些实现确实允许八进制文字。)< /p>在严格模式下,标识符
eval 和
arguments
被视为关键字,您不能更改它们的值,不能为它们赋值,也不能将它们用作变量、函数、函数参数或 catch 块的标识符。在严格模式下,对检查调用堆栈的可能性有更多限制。
arguments.caller
和arguments.callee
在严格模式下的函数中导致TypeError
。此外,当您尝试读取严格模式下函数的某些调用者属性和参数属性时,它们会导致TypeError
。I would like to offer a somewhat more founded answer complementing the other answers. I was hoping to edit the most popular answer, but failed. I tried to make it as comprehensive and complete as I could.
You can refer to the MDN documentation for more information.
"use strict"
a directive introduced in ECMAScript 5.Directives are similar to statements, yet different.
use strict
does not contain key words: The directive is a simple expression statement, which consists of a special string literal (in single or double quotes). JavaScript engines, that do not implement ECMAScript 5, merely see an expression statement without side effects. It is expected that future versions of ECMAScript standards introduceuse
as a real key word; the quotes would thereby become obsolete.use strict
can be used only at the beginning of a script or of a function, i.e. it must precede every other (real) statement. It does not have to be the first instruction in a script of function: it can be preceded by other statement expressions that consist of string literals ( and JavaScript implementations can treat them as implementation specific directives). String literals statements, which follow a first real statement (in a script or function) are simple expression statements. Interpreters must not interpret them as directives and they have no effect.The
use strict
directive indicates that the following code (in a script or a function) is strict code.The code in the highest level of a script (code that is not in a function) is considered strict code when the script contains a
use strict
directive.The content of a function is considered strict code when the function itself is defined in a strict code or when the function contains a
use strict
directive.Code that is passed to an
eval()
method is considered strict code wheneval()
was called from a strict code or contains theuse strict
directive itself.The strict mode of ECMAScript 5 is a restricted subset of the JavaScript language, which eliminates relevant deficits of the language and features more stringent error checking and higher security. The following lists the differences between strict mode and normal mode (of which the first three are particularly important):
with
-statement in strict mode.Object
, then you will get aReferenceError
. In normal mode the identifier is implicitly declared as a global variable (as a property of the globalObject
)this
has the valueundefined
in functions that were invoked as functions (not as methods). (In normal modethis
always points to the globalObject
). This difference can be used to test if an implementation supports the strict mode:Also when a function is invoked with
call()
orapply
in strict mode, thenthis
is exactly the value of the first argument of thecall()
orapply()
invocation. (In normal modenull
andundefined
are replaced by the globalObject
and values, which are not objects, are cast into objects.)In strict mode you will get a
TypeError
, when you try to assign to readonly properties or to define new properties for a non extensible object. (In normal mode both simply fail without error message.)In strict mode, when passing code to
eval()
, you cannot declare or define variables or functions in the scope of the caller (as you can do it in normal mode). Instead, a new scope is created foreval()
and the variables and functions are within that scope. That scope is destroyed aftereval()
finishes execution.In strict mode the arguments-object of a function contains a static copy of the values, which are passed to that function. In normal mode the arguments-object has a somewhat "magical" behaviour: The elements of the array and the named function parameters reference both the same value.
In strict mode you will get a
SyntaxError
when thedelete
operator is followed by a non qualified identifier (a variable, function or function parameter). In normal mode thedelete
expression would do nothing and is evaluated tofalse
.In strict mode you will get a
TypeError
when you try to delete a non configurable property. (In normal mode the attempt simply fails and thedelete
expression is evaluated tofalse
).In strict mode it is considered a syntactical error when you try to define several properties with the same name for an object literal. (In normal mode there is no error.)
In strict mode it is considered a syntactical error when a function declaration has multiple parameters with the same name. (In normal mode there is no error.)
In strict mode octal literals are not allowed (these are literals that start with
0
. (In normal mode some implementations do allow octal literals.)In strict mode the identifiers
eval
andarguments
are treated like keywords. You cannot change their value, cannot assign a value to them, and you cannot use them as names for variables, functions, function parameters or identifiers of a catch block.In strict mode are more restrictions on the possibilities to examine the call stack.
arguments.caller
andarguments.callee
cause aTypeError
in a function in strict mode. Furthermore, some caller- and arguments properties of functions in strict mode cause aTypeError
when you try to read them.我的两分钱:
严格模式的目标之一是允许更快地调试问题。当发生某些可能导致沉默和失败的错误事情时,它可以通过抛出异常来帮助开发人员。您的网页的奇怪行为。当我们使用
use strict
时,代码会抛出错误,帮助开发人员提前修复它。使用
use strict
后我学到了一些重要的事情:防止全局变量声明:
现在,此代码在全局范围内创建
nameoftree
,可以使用window.nameoftree
访问它。当我们实现use strict
时,代码会抛出错误。消除
with
语句:with
语句无法使用with
等工具进行缩小a href="http://marijnhaverbeke.nl/uglifyjs" rel="noreferrer">uglify-js。它们也被弃用并从未来的 JavaScript 版本中删除。样本:
防止重复:
当我们有重复的属性时,它会抛出异常
还有一些,但我需要获得更多这方面的知识。
My two cents:
One of the goals of strict mode is to allow for faster debugging of issues. It helps the developers by throwing exception when certain wrong things occur that can cause silent & strange behaviour of your webpage. The moment we use
use strict
, the code will throw out errors which helps developer to fix it in advance.Few important things which I have learned after using
use strict
:Prevents Global Variable Declaration:
Now,this code creates
nameoftree
in global scope which could be accessed usingwindow.nameoftree
. When we implementuse strict
the code would throw error.Eliminates
with
statement :with
statements can't be minified using tools like uglify-js. They're also deprecated and removed from future JavaScript versions.Sample:
Prevents Duplicates :
When we have duplicate property, it throws an exception
There are few more but I need to gain more knowledge on that.
如果您使用去年左右发布的浏览器,那么它很可能支持 JavaScript 严格模式。只有 ECMAScript 5 成为当前标准之前的旧版浏览器不支持它。
命令周围的引号确保代码仍然可以在较旧的浏览器中工作(尽管在严格模式下生成语法错误的东西通常只会导致脚本在这些较旧的浏览器中以某种难以检测的方式出现故障)。
If you use a browser released in the last year or so then it most likely supports JavaScript Strict mode. Only older browsers around before ECMAScript 5 became the current standard don't support it.
The quotes around the command make sure that the code will still work in older browsers as well (although the things that generate a syntax error in strict mode will generally just cause the script to malfunction in some hard to detect way in those older browsers).
添加
"use strict";
时,以下情况将在脚本执行之前抛出 SyntaxError:为未来的 ECMAScript 版本铺平道路,使用新保留的关键字之一(在 ECMAScript 6 的预置中):
implements
、interface
、let
、包
、私有
、受保护
、公共
、静态
和yield
。在块中声明函数
八进制语法
<前><代码>var n = 023;
this
指向全局对象。在对象文字中为属性名称声明两次相同的名称
<前><代码> {a:1,b:3,a:7}
ECMAScript 6 中不再出现这种情况(bug 1041128)。
声明两个具有相同名称函数的函数参数
为未声明的变量设置值
对变量名称使用
delete
delete myVariable;
使用
eval
或arguments
作为变量或函数参数名称来源:
在 MDN 上过渡到严格模式
MDN 上的严格模式
JavaScript 的严格模式以及为什么应该在 Colin 上使用它 J. Ihrig 的博客(存档版本)
When adding
"use strict";
, the following cases will throw a SyntaxError before the script is executing:Paving the way for future ECMAScript versions, using one of the newly reserved keywords (in prevision for ECMAScript 6):
implements
,interface
,let
,package
,private
,protected
,public
,static
, andyield
.Declaring function in blocks
Octal syntax
this
point to the global object.Declaring twice the same name for a property name in an object literal
This is no longer the case in ECMAScript 6 (bug 1041128).
Declaring two function arguments with the same name function
Setting a value to an undeclared variable
Using
delete
on a variable namedelete myVariable;
Using
eval
orarguments
as variable or function argument nameSources:
Transitioning to strict mode on MDN
Strict mode on MDN
JavaScript’s Strict Mode and Why You Should Use It on Colin J. Ihrig's blog (archived version)
严格模式对正常 JavaScript 语义进行了一些更改:
通过更改消除一些 JavaScript 无提示错误
抛出错误。
修复了使 JavaScript 变得困难的错误
引擎执行优化。
禁止将来可能定义的某些语法
ECMAScript 版本。
有关更多信息,请访问严格模式 - Javascript
Strict mode makes several changes to normal JavaScript semantics:
eliminates some JavaScript silent errors by changing them
to throw errors.
fixes mistakes that make it difficult for JavaScript
engines to perform optimizations.
prohibits some syntax likely to be defined in future
versions of ECMAScript.
for more information vistit Strict Mode- Javascript
“严格使用”;是程序员不会使用 JavaScript 的松散或不良属性的保证。它是一个指南,就像一把尺子可以帮助你画直线一样。 “使用严格”将帮助您进行“直接编码”。
那些不喜欢使用标尺来画直线的人通常会在那些页面中要求其他人调试他们的代码。
相信我。与设计不良的代码相比,开销可以忽略不计。 Doug Crockford,曾是一名高级多年的 JavaScript 开发人员,这里有一篇非常有趣的文章。就我个人而言,我喜欢一直返回他的网站,以确保我不会忘记我的良好实践。
现代 JavaScript 实践应该始终唤起“严格使用”; pragma。ECMA 集团将“严格”模式设为可选的唯一原因是允许经验不足的编码人员访问 JavaScript,并给他们时间来适应新的、更安全的编码实践。 >
"Use Strict"; is an insurance that programmer will not use the loose or the bad properties of JavaScript. It is a guide, just like a ruler will help you make straight lines. "Use Strict" will help you do "Straight coding".
Those that prefer not to use rulers to do their lines straight usually end up in those pages asking for others to debug their code.
Believe me. The overhead is negligible compared to poorly designed code. Doug Crockford, who has been a senior JavaScript developer for several years, has a very interesting post here. Personally, I like to return to his site all the time to make sure I don't forget my good practice.
Modern JavaScript practice should always evoke the "Use Strict"; pragma. The only reason that the ECMA Group has made the "Strict" mode optional is to permit less experienced coders access to JavaScript and give then time to adapt to the new and safer coding practices.
从现在开始,在所有敏感 JavaScript 文件的开头包含
use strict
是成为更好的 JavaScript 程序员并避免随机变量成为全局变量和悄然发生变化的一个小方法。Including
use strict
in the beginning of your all sensitive JavaScript files from this point is a small way to be a better JavaScript programmer and avoid random variables becoming global and things change silently.引用自 w3schools:
请参考http://www.w3schools.com/js/js_strict.asp了解更多
Quoting from w3schools:
Please refer to http://www.w3schools.com/js/js_strict.asp to know more
“use strict”
使 JavaScript 代码在严格模式下运行,这基本上意味着所有内容都需要在使用前定义。使用严格模式的主要原因是为了避免意外的全局使用未定义的方法。此外,在严格模式下,运行速度更快,一些警告或静默警告会引发致命错误,最好始终使用它来编写更简洁的代码。
"use strict"
在 ECMA5 中被广泛使用,在 ECMA6 中它默认是 JavaScript 的一部分,所以如果你使用的话不需要添加它ES6。请看 MDN 中的这些陈述和示例:
1) 函数中的严格模式
2) 全脚本严格模式
3) 分配给不可写的全局
您可以 在 MDN 上了解更多信息。
"use strict"
makes JavaScript code to run in strict mode, which basically means everything needs to be defined before use. The main reason for using strict mode is to avoid accidental global uses of undefined methods.Also in strict mode, things run faster, some warnings or silent warnings throw fatal errors, it's better to always use it to make a neater code.
"use strict"
is widely needed to be used in ECMA5, in ECMA6 it's part of JavaScript by default, so it doesn't need to be added if you're using ES6.Look at these statements and examples from MDN:
1) strict mode in functions
2) whole-script strict mode
3) Assignment to a non-writable global
You can read more on MDN.
ECMAScript 委员会的一些人发表了一篇精彩的演讲:JavaScript 的更改,第 1 部分:ECMAScript 5 ” 关于渐进式使用
“use strict”
开关如何允许 JavaScript 实现者清理 JavaScript 的许多危险功能,而不会突然破坏世界上的每个网站。当然,它也讨论了其中许多缺陷是什么以及 ECMAScript 5 如何修复它们。
There's a good talk by some people who were on the ECMAScript committee: Changes to JavaScript, Part 1: ECMAScript 5" about how incremental use of the
"use strict"
switch allows JavaScript implementers to clean up a lot of the dangerous features of JavaScript without suddenly breaking every website in the world.Of course it also talks about just what a lot of those misfeatures are (were) and how ECMAScript 5 fixes them.
比较的小例子:
非严格模式:
严格模式:
非严格模式:
Small examples to compare:
Non-strict mode:
Strict mode:
Non-strict mode:
请注意,
use strict
是在 EcmaScript 中引入的5 并从那时起一直保留。以下是 ES6 和 ES7:
Note that
use strict
was introduced in EcmaScript 5 and was kept since then.Below are the conditions to trigger strict mode in ES6 and ES7:
开发人员应使用
“use strict”
的主要原因是:防止意外声明全局变量。使用
“use strict()”
将确保变量使用前用var
声明。例如:
"use strict"
指令仅在脚本或函数的开头被识别。字符串
“arguments”
不能用作变量:将限制关键字作为变量的使用。尝试使用它们会引发错误。
简而言之,将使您的代码不易出错,进而使您编写出好的代码。
要了解更多相关信息,您可以参考此处。
The main reasons why developers should use
"use strict"
are:Prevents accidental declaration of global variables.Using
"use strict()"
will make sure that variables are declared withvar
before use.Eg:
"use strict"
directive is only recognized at the beginning of a script or a function.The string
"arguments"
cannot be used as a variable:Will restrict uses of keywords as variables. Trying to use them will throw errors.
In short will make your code less error prone and in turn will make you write good code.
To read more about it you can refer here.
use strict
是一种让代码更安全的方法,因为您不能使用无法按预期工作的危险功能。而且,正如之前所写,它使代码更加严格。use strict
is a way to make your code safer, because you can't use dangerous features that can work not as you expect. And, as was written before, it makes code more strict.“严格使用”; ECMA 致力于让 JavaScript 变得更加健壮。它引入了 JS,试图使其至少有点“严格”(其他语言自 90 年代以来就实施了严格的规则)。它实际上“迫使”JavaScript 开发人员遵循某种编码最佳实践。
尽管如此,JavaScript 仍然非常脆弱。不存在类型变量、类型方法等。
我强烈建议 JavaScript 开发人员学习更强大的语言,例如 Java 或 ActionScript3,并在 JavaScript 代码中实现相同的最佳实践,它将工作得更好并且更容易调试。
"use strict"; is the ECMA effort to make JavaScript a little bit more robust. It brings in JS an attempt to make it at least a little "strict" (other languages implement strict rules since the 90s). It actually "forces" JavaScript developers to follow some sort of coding best practices.
Still, JavaScript is very fragile. There is no such thing as typed variables, typed methods, etc.
I strongly recommend JavaScript developers to learn a more robust language such as Java or ActionScript3, and implement the same best practices in your JavaScript code, it will work better and be easier to debug.
JavaScript“严格”模式是在 ECMAScript 5 中引入的。在
JS 文件的最顶部编写
"use strict";
会开启严格模式语法检查。它为我们执行以下任务:
如果您尝试分配给未声明的变量,则显示错误
阻止您覆盖关键 JS 系统库
禁止一些不安全或容易出错的语言功能
use strict
也可以在个人职能。在代码中包含use strict
始终是更好的做法。浏览器兼容性问题:
“use”指令旨在向后兼容。不支持它们的浏览器只会看到未进一步引用的字符串文字。因此,他们会跳过它并继续前进。
JavaScript “strict” mode was introduced in ECMAScript 5.
Writing
"use strict";
at the very top of your JS file turns on strictsyntax checking. It does the following tasks for us:
shows an error if you try to assign to an undeclared variable
stops you from overwriting key JS system libraries
forbids some unsafe or error-prone language features
use strict
also works inside of individual functions. It is always a better practice to includeuse strict
in your code.Browser compatibility issue:
The "use" directives are meant to be backwards-compatible. Browsers that do not support them will just see a string literal that isn't referenced further. So, they will pass over it and move on.
Use Strict 用于显示常见和重复的错误,以便以不同的方式对其进行处理,并更改 java 脚本的运行方式,这些更改是:
防止意外全局变量
无重复
消除
消除此强制
更安全的 eval()
不可变错误
p>
您还可以阅读此 文章了解详细信息
Use Strict is used to show common and repeated errors so that it is handled differently , and changes the way java script runs , such changes are :
Prevents accidental globals
No duplicates
Eliminates with
Eliminates this coercion
Safer eval()
Errors for immutables
you can also read this article for the details
通常,JavaScript 不遵循严格的规则,因此增加了出错的机会。使用
“use strict”
后,JavaScript代码应该像其他编程语言一样遵循严格的规则集,例如使用终止符、初始化之前的声明等。如果
“use strict” 时,应遵循一组严格的规则来编写代码,从而减少出现错误和歧义的机会。
Normally, JavaScript does not follow strict rules, hence increasing chances of errors. After using
"use strict"
, the JavaScript code should follow strict set of rules as in other programming languages such as use of terminators, declaration before initialization, etc.If
"use strict"
is used, the code should be written by following a strict set of rules, hence decreasing the chances of errors and ambiguities.“使用严格”;定义 JavaScript 代码应在以下位置执行
“严格模式”。
JavaScript 的版本。
在“严格模式”下执行。
所有现代浏览器都支持“use strict”,Internet Explorer 9 及更低版本除外。
缺点
如果开发人员使用严格模式下的库,但开发人员习惯在正常模式下工作,他们可能会对库调用一些无法按预期工作的操作。
更糟糕的是,由于开发人员处于正常模式,他们没有抛出额外错误的优势,因此错误可能会默默地失败。
此外,如上所述,严格模式会阻止您执行某些操作。
人们通常认为一开始就不应该使用这些东西,但有些开发人员不喜欢这种约束,并希望使用该语言的所有功能。
有关基本示例和参考,请访问:
https://www.tutorialsteacher.com/javascript/javascript-strict< /p>
"use strict"; Defines that JavaScript code should be executed in
"strict mode".
versions of JavaScript.
executed in "strict mode".
All modern browsers support "use strict" except Internet Explorer 9 and lower.
Disadvantage
If a developer used a library that was in strict mode, but the developer was used to working in normal mode, they might call some actions on the library that wouldn’t work as expected.
Worse, since the developer is in normal mode, they don’t have the advantages of extra errors being thrown, so the error might fail silently.
Also, as listed above, strict mode stops you from doing certain things.
People generally think that you shouldn’t use those things in the first place, but some developers don’t like the constraint and want to use all the features of the language.
For basic example and for reference go through :
https://www.tutorialsteacher.com/javascript/javascript-strict
由于浏览器之争和管理不善,JavaScript 的设计和实现仓促。结果,许多糟糕的设计决策、不直观的语法和令人困惑的语义都出现在该语言中。严格模式旨在修正其中一些错误。
但是在不创建替代解释的情况下修复这些错误会破坏向后兼容性。因此,“use strict”指令在将代码传达给程序员时创建了代码的替代解释。
例如,
this
关键字指的是方法定义中的对象,就像其他语言中的this
或self
一样。this
在方法上下文之外没有任何用途,但所有 JavaScript 函数都有this
关键字,无论它们是否是方法:这里
this
解析为全局对象这没有意义,也没有任何作用,因为全局对象已经在作用域中可用。在严格模式下,全局函数中的 this 会解析为 undefined,这正是我们所期望的。
即使在严格模式下,某些错误也无法修复,因为语法对于旧版浏览器应该是有效的,因为它们忽略了“严格模式”指令。这是设计使然。
JavaScript was designed and implemented hastily because of the browser wars and bad management. As a result many poor design decisions, un-intuitive syntax and confusing semantics found their way into the language. Strict mode aims to amend some of these mistakes.
But fixing these mistakes without creating alternative interpretation breaks backward compatibility. So,
"use strict"
directive creates that alternative interpretation of the code while communicating it to the programmer.For example,
this
keywords refers to the object in a method definition, likethis
orself
in other languages.this
has no purpose outside the method context but all JavaScript functions havethis
keyword whether they are methods or not:Here
this
resolves to the global object which does not make sense and serves no purpose because global object is already available in the scope.In strict mode
this
in a global function resolves to undefined, which is what we expect.Some mistakes can not be fixed even in strict mode because syntax should be valid for older browsers since they ignore
"strict mode"
directive. This is by design.严格模式可以防止内存泄漏。
请检查下面以非严格模式编写的函数:
在这个函数中,我们在函数内部使用了一个名为
name
的变量。在内部,编译器将首先检查在该特定函数作用域中是否存在使用该特定名称声明的任何变量。由于编译器知道不存在这样的变量,因此它将检查外部作用域。在我们的例子中,它是全局范围。同样,编译器知道在全局空间中也没有使用该名称声明的变量,因此它在全局空间中为我们创建了这样一个变量。从概念上讲,该变量将在全局范围内创建,并且在整个应用程序中可用。另一种情况是,变量是在子函数中声明的。在这种情况下,编译器会检查外部作用域(即父函数)中该变量的有效性。只有这样它才会检查全局空间并在那里为我们创建一个变量。
这意味着需要进行额外的检查。这将影响应用程序的性能。
现在让我们在严格模式下编写相同的函数。
我们会得到以下错误。
在这里,编译器抛出引用错误。在严格模式下,编译器不允许我们在未声明的情况下使用该变量。因此可以防止内存泄漏。另外,我们还可以编写更加优化的代码。
Strict mode can prevent memory leaks.
Please check the function below written in non-strict mode:
In this function, we are using a variable called
name
inside the function. Internally, the compiler will first check if there is any variable declared with that particular name in that particular function scope. Since the compiler understood that there is no such variable, it will check in the outer scope. In our case, it is the global scope. Again, the compiler understood that there is also no variable declared in the global space with that name, so it creates such a variable for us in the global space. Conceptually, this variable will be created in the global scope and will be available in the entire application.Another scenario is that, say, the variable is declared in a child function. In that case, the compiler checks the validity of that variable in the outer scope, i.e., the parent function. Only then it will check in the global space and create a variable for us there.
That means additional checks need to be done. This will affect the performance of the application.
Now let's write the same function in strict mode.
We will get the following error.
Here, the compiler throws the reference error. In strict mode, the compiler does not allow us to use the variable without declaring it. So memory leaks can be prevented. In addition, we can write more optimized code.
严格模式消除了在非严格模式下会被忽略的错误,从而使 javascript “更安全”。
是的,在使用 javascript 时,它被认为是最佳实践的一部分,包括严格模式。这是通过在 JS 文件中添加以下代码行来完成的。
'使用严格';
在你的代码中。
指示应以严格模式解释代码向浏览器等用户代理指定,它们应按字面意思对待代码,如果代码没有意义,则抛出错误。
例如:假设您的
.js
文件中有以下代码:场景 1:[无严格模式]
场景 2: [无严格模式]
如果没有打开严格模式,用户代理通常会对有问题的代码进行一系列修改,试图使其有意义。从表面上看,这似乎是一件好事,事实上,在严格模式之外工作使得人们可以在没有完全确定所有细节的情况下开始使用 JavaScript 代码。然而,作为一名开发人员,我不想在代码中留下错误,因为我知道它稍后可能会回来咬我,而且我也只想编写好的代码。这就是严格模式可以发挥作用的地方。
场景 3:[严格模式]
其他提示:要使用严格模式保持代码质量,您不需要一遍又一遍地编写此内容特别是如果您有多个
.js
文件。您可以在 eslint 规则中全局强制执行此规则,如下所示:文件名:
.eslintrc.js
使用变量而不声明它将在严格模式下引发错误。这是为了防止在整个应用程序中无意中创建全局变量。芝加哥印刷的例子特别涵盖了这一点。
删除变量、函数或参数在严格模式下是禁忌。
在严格模式下不允许重复参数名称。
严格模式下不允许使用 Javascript 语言中的保留字。这些词是实现接口、let、包、私有、受保护、公共。静态和产量
请查看此处的 MDN 文档: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
Strict mode eliminates errors that would be ignored in non-strict mode, thus making javascript “more secured”.
Yes, It's considered part of the best practices while working with javascript to include Strict mode. This is done by adding the below line of code in your JS file.
'use strict';
in your code.
Indicating that code should be interpreted in strict mode specifies to user agents like browsers that they should treat code literally as written, and throw an error if the code doesn't make sense.
For example: Consider in your
.js
file you have the following code:Scenario 1: [NO STRICT MODE]
Scenario 2: [NO STRICT MODE]
Without strict mode turned on, user agents often go through a series of modifications to problematic code in an attempt to get it to make sense. On the surface, this can seem like a fine thing, and indeed, working outside of strict mode makes it possible for people to get their feet wet with JavaScript code without having all the details quite nailed down. However, as a developer, I don't want to leave a bug in my code, because I know it could come back and bite me later on, and I also just want to write good code. And that's where strict mode helps out.
Scenario 3: [STRICT MODE]
Additional tip: To maintain code quality using strict mode, you don't need to write this over and again especially if you have multiple
.js
file. You can enforce this rule globally ineslint
rules as follows:Filename:
.eslintrc.js
Using a variable without declaring it will throw an error in strict mode. This is to prevent unintentionally creating global variables throughout your application. The example with printing Chicago covers this in particular.
Deleting a variable or a function or an argument is a no-no in strict mode.
Duplicating a parameter name is not allowed in strict mode.
Reserved words in the Javascript language are not allowed in strict mode. The words are implements interface, let, packages, private, protected, public. static, and yield
For a more comprehensive list check out the MDN documentation here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Strict_mode
严格模式在 v8 引擎中启用严格功能。一些功能的简短示例:
您可以通过编写全局启用它:
每个函数,您只需在函数中包含:
es6功能已启用(这是与浏览器相关的),对于节点 v4+ 这很重要。
在某些情况下,性能会更好。
还有更多功能,请查看此处了解更多的!
strict mode enables strict features in the v8 engine. Short example of some features:
You can enable it globally by writing:
Per function you just include in function:
es6 features are enabled (this is browser dependent), for node v4+ this is important.
Performance, in some cases, is better.
There are more features as well, check here for more!