我应该为我编写的每个 JavaScript 函数“使用严格”吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34301881/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:30:41  来源:igfitidea点击:

Should I 'use strict' for every single javascript function I write?

javascriptstrict-mode

提问by Won Jun Bae

Should I 'use strict' for every single javascript function I write?

我应该为我编写的每个 JavaScript 函数“使用严格”吗?

What is a good practice to use strict in a large AngularJS project? Using it globally can break a third party library that doesn't support it, but doing 'use strict' every single time is just a lot of repetition.

在大型 AngularJS 项目中使用 strict 的好做法是什么?全局使用它可以破坏不支持它的第三方库,但是每次都执行“严格使用”只是大量重复。

采纳答案by jeff_mcmahan

On this question, do beware a general tendency to oversimplify.

在这个问题上,请注意过度简化的普遍趋势。

First, all of your code absolutely should be runin strict mode. Core modern javascript functionality is changed (see .call() and apply()) or disfigured (silent Errors) by executing code outside of strict mode. (More on this here, from Crockford.)

首先,您的所有代码绝对应该在严格模式下运行。通过在严格模式之外执行代码,现代 javascript 的核心功能被改变(见.call() 和 apply())或毁容(静默错误)。(更多关于这里的信息,来自克罗克福德。)

However, that doesn't address howyou should ensure that your code runs in strict mode. There are at least two contexts to consider:

但是,这并没有解决您应该如何确保您的代码在严格模式下运行。至少有两种情况需要考虑:

In the browser, your code should be delivered after being minified. If you include 'use strict'in every function body, your minifier won't strip it out, and you'll waste bytes repeating it everywhere. You only need it in your outermost function scope(s)—at the top of your module definitions. One approach is to wrap your minified code in a single IIFE closure as part of the build process:

在浏览器中,您的代码应在缩小后交付。如果你包含'use strict'在每个函数体中,你的压缩器不会把它去掉,你会浪费字节到处重复它。您只需要在最外层的函数作用域(模块定义的顶部)中使用它。作为构建过程的一部分,一种方法是将缩小的代码包装在单个 IIFE 闭包中:

;(function (){ 
  'use strict'
  // All code here.
}())

This, I think, is close to the ideal way of doing it, but it more or less dictates that you adopt a continuous integration workflow (since, to observe your code running in strict mode, you must have it all wrapped up one closure). If you don't work that way, you'll have to include the use strictdirective at the top of every function that isn't being declared within another function's scope.

我认为,这接近于理想的实现方式,但它或多或少要求您采用持续集成工作流(因为要观察在严格模式下运行的代码,您必须将其全部封装在一个闭包中) . 如果您不这样做,则必须use strict在每个未在另一个函数的作用域内声明的函数的顶部包含该指令。

On the server, it's much simpler, of course. Code isn't minified, and bytes don't matter, so you can just include the use strictdirective at the top of every file.

在服务器上,当然要简单得多。代码没有被压缩,字节也无关紧要,因此您可以use strict在每个文件的顶部包含该指令。

A word of warning on --use_strict: In cases where you control how scripts are run, you may find yourself tempted to use the --use_strictruntime flag. It's easy, but it means all dependenciesmust be strict mode compliant. Since you can't control every third-party's compliance, this is usually unwise.

警告--use_strict:在您控制脚本运行方式的情况下,您可能会发现自己很想使用--use_strict运行时标志。这很容易,但这意味着所有依赖项都必须符合严格模式。由于您无法控制每个第三方的合规性,因此这通常是不明智的。

回答by Bergi

Allcode you write1shouldbe in strict mode. It helps you catch mistakesby not ignoring exceptions.

您编写的所有代码1都应处于严格模式。它通过不忽略异常来帮助您发现错误

However, no, this does not mean that you need to prepend "use strict";to every functiondefinition, you only should put it in the module scope - once per file - so that it is inherited by all your functions. When you're going to switch to ES6 modules it will be impliedanyway.

但是,,这并不意味着您需要预先添加"use strict";到每个function定义,您只应该将它放在模块范围内 - 每个文件一次 - 以便它被您的所有函数继承。当你要切换到 ES6 模块时,无论如何都会被暗示

1: I'd even argue for enabling it globally, as strict mode should not break any properly written code.
If it doesbreak a third party script, the solution might not be to disable strict mode again…

1:我什至主张在全球范围内启用它,因为严格模式不应该破坏任何正确编写的代码。
如果它确实破坏了第三方脚本,解决方案可能不是再次禁用严格模式......

回答by Praveen Kumar Purushothaman

Short answer, yes! You don't need to include it for every function, but rather you can just add it once per JavaScript file. When you start the file, start with a closure like this:

简短的回答,是的!您不需要为每个函数都包含它,而只需为每个 JavaScript 文件添加一次即可。当你启动文件时,从一个像这样的闭包开始:

(function () {
  "use strict";
  // Rest of your code.

})();

回答by Douglas Daseeco

No. The redundancy is not necessary. Use of the declaration

不,冗余不是必需的。声明的使用

"use strict";

at the file or stream scope is preferable, especially if third party libraries are used. It helps decide whether to use them as is, wrap them, or pass on using them.

在文件或流范围内更可取,尤其是在使用第三方库的情况下。它有助于决定是按原样使用它们、包装它们还是继续使用它们。

File Level Self-executing Functions

文件级自执行函数

It is becoming more common to see entire files or streams in self-executing closures. In such cases, the declaration to use strict mode (above) is inserted in the first line of the closure, where the ... is.

在自执行闭包中看到整个文件或流变得越来越普遍。在这种情况下,使用严格模式(上面)的声明被插入到闭包的第一行,其中 ... 所在的位置。

(function () { 
    ...
}())

It may be useful to mention that self-execution is not always necessary and can actually cause sluggish loads and other problems if overused.

值得一提的是,自我执行并不总是必要的,如果过度使用,实际上可能会导致加载缓慢和其他问题。

More on Scope of Declaration

更多关于声明范围

The scope of is dependent on whether you place the declaration inside or outside a function and applies to all statements following the declaration within the closure's scope.

的范围取决于您是将声明放在函数内部还是外部,并适用于闭包范围内声明之后的所有语句。

Use of the declaration inside the function is the wrong way to do it if all of the file or stream is already compatible with the stricter mode or can be made so with ease. The redundancy is unnecessary, so placing the declaration on the top of the file or beginning of the stream is the recommended use.

如果所有文件或流都已经与更严格的模式兼容或可以轻松实现,则在函数内部使用声明是错误的方法。冗余是不必要的,因此建议将声明放在文件的顶部或流的开头。

Sometimes only some of the functions comply with the stricter rules. In such cases the less desirable function scope of the declaration can be used to encourage finer coding practices at least in the functions that already comply.

有时只有部分功能符合更严格的规则。在这种情况下,声明的不太理想的功能范围可用于鼓励至少在已经遵守的功能中进行更精细的编码实践。

Why Strict Mode At All?

为什么要严格模式?

Strict mode eliminates certain permissive language parsing and execution characteristics deemed less desirable from a language design point of view. These non-strict mode language characteristics were deemed prudent as default behavior for backward compatibility. The synopsis and details appear here.

从语言设计的角度来看,严格模式消除了某些被认为不太理想的宽松语言解析和执行特征。这些非严格模式语言特性被视为向后兼容的默认行为。概要和详细信息显示在此处。

It is not unambiguously defined when and if these older language characteristics from the early Netscape days will be deprecated or whether strict mode will become default behavior across browsers at some point, but the stricter model is likely to produce less ambiguous and risky source. If you wish to improving maintainability, portability, and extensibility in coding practice and code bases, then strict mode is a good option.

没有明确定义这些早期 Netscape 时代的旧语言特征何时以及是否会被弃用,或者严格模式是否会在某个时候成为跨浏览器的默认行为,但更严格的模型可能会产生更少的歧义和风险。如果您希望提高编码实践和代码库的可维护性、可移植性和可扩展性,那么严格模式是一个不错的选择。



NOTEFor those coming here from "What's the benefit of using "function() 'use strict'” in every file?"

注意对于那些从“在每个文件中使用“function() 'use strict'”有什么好处?

You can place

你可以放置

"use strict";

on the top of the code sequence or inside the function, so it is only one line of code per file or per function.

在代码序列的顶部或函数内部,因此每个文件或每个函数只有一行代码。

The other lines of code have other purposes in the code here.

其他代码行在此处的代码中有其他用途。

  • Self-invoking function
  • Factory invocation
  • 自调用函数
  • 工厂调用

Some place the entire file in a self-executing function, but that is not necessary in every case.

有些人将整个文件放在一个自执行函数中,但这并不是在所有情况下都必需的。