【发布时间】:2016-12-15 09:01:48
【问题描述】:
我包括声明:
"use strict";
在我的大多数 Javascript 文件的开头。
JSLint 以前从未警告过这一点。但现在是,说:
使用“use strict”的函数形式。
有人知道“函数形式”是什么吗?
【问题讨论】:
标签: javascript jslint
我包括声明:
"use strict";
在我的大多数 Javascript 文件的开头。
JSLint 以前从未警告过这一点。但现在是,说:
使用“use strict”的函数形式。
有人知道“函数形式”是什么吗?
【问题讨论】:
标签: javascript jslint
包含'use strict'; 作为包装函数中的第一条语句,因此它只影响该函数。这可以防止在连接不严格的脚本时出现问题。
查看 Douglas Crockford 的最新博文 Strict Mode Is Coming To Town。
该帖子的示例:
(function () {
'use strict';
// this function is strict...
}());
(function () {
// but this function is sloppy...
}());
更新: 如果您不想包装立即功能(例如它是一个节点模块),那么您可以禁用警告。
对于 JSLint(根据 Zhami):
/*jslint node: true */
对于JSHint:
/*jshint strict:false */
或(根据Laith Shadeed)
/* jshint -W097 */
要禁用来自 JSHint 的任意警告,请查看 JSHint source code 中的地图(docs 中的详细信息)。
更新 2: JSHint 支持 node:boolean 选项。见.jshintrc at github。
/* jshint node: true */
【讨论】:
-1
/*jshint strict:false */,以便更清楚地了解您在做什么(除非我不知道您的数字代码有什么特别的好处)
"use strict";。
字符串形式本身并没有错。
与其避免“全局”严格形式来担心连接非严格 javascript,不如将该死的非严格 javascript 修复为严格形式。
【讨论】:
这很简单:如果您想对所有代码都严格要求,请在 JavaScript 开头添加 "use strict";。
但是,如果您只想对某些代码严格,请使用函数形式。无论如何,我建议你在 JavaScript 的开头使用它,因为这将帮助你成为更好的编码器。
【讨论】:
"use strict"; 放在我的 JS 文件的顶部时,我确实得到了这个错误,所以这可能并不完全正确。
"use strict"; 的“全局”形式,它只是放在代码的顶部。它只允许 "use strict;" 包装在函数中。 (不过,JS_Hint_ 允许您使用全局表单——有关所需设置,请参见上面的答案)。
如果您正在为 NodeJS 编写模块,它们已经被封装了。通过包含在文件顶部告诉 JSLint 你已经获得了节点:
/*jslint node: true */
【讨论】:
/*jshint strict:false */
"node": true 添加到 .jshintrc
我建议改用jshint。
它允许通过/*jshint globalstrict: true*/ 抑制此警告。
如果你正在编写一个库,我只建议在你的代码像 nodejs 一样被封装到模块中时使用 global strict。
否则你会强制所有使用你的库的人进入严格模式。
【讨论】:
strict: 'global',看看jshint.com/docs/options/#globalstrict
我在 Cross Platform JavaScript 博客文章之后开始创建 Node.js/browserify 应用程序。我遇到了这个问题,因为我全新的 Gruntfile 没有通过 jshint。
幸运的是我在Leanpub book on Grunt找到了答案:
如果我们现在尝试,我们将扫描我们的 Gruntfile……并得到一些错误:
$ grunt jshint Running "jshint:all" (jshint) task Linting Gruntfile.js...ERROR [L1:C1] W097: Use the function form of "use strict". 'use strict'; Linting Gruntfile.js...ERROR [L3:C1] W117: 'module' is not defined. module.exports = function (grunt) { Warning: Task "jshint:all" failed. Use --force to continue.这两个错误都是因为 Gruntfile 是一个 Node 程序,默认情况下 JSHint 不识别或不允许使用
module和use strict的字符串版本。我们可以设置一个 JSHint 规则来接受我们的 Node 程序。让我们编辑我们的 jshint 任务配置并添加一个选项键:jshint: { options: { node: true }, }
将 node: true 添加到 jshint options,以将 jshint 置于“节点模式”,为我消除了这两个错误。
【讨论】:
在项目的根目录中添加一个文件 .jslintrc(或 .jshintrc,如果是 jshint),其内容如下:
{
"node": true
}
【讨论】:
我想每个人都错过了这个问题的“突然”部分。很可能,您的 .jshintrc 有语法错误,因此它不包括“浏览器”行。通过 json 验证器运行它以查看错误在哪里。
【讨论】:
process.on('warning', function(e) {
'use strict';
console.warn(e.stack);
});
process.on('uncaughtException', function(e) {
'use strict';
console.warn(e.stack);
});
将此行添加到文件的起点
【讨论】: