由于函数排序,JSLint"超出范围"错误?

Cod*_*key 6 javascript jslint

JSLint似乎对函数排序很挑剔.

这很好:

function a() {
    'use strict';
    return 1;
}

function b() {
    'use strict';
    a();
}
Run Code Online (Sandbox Code Playgroud)

虽然这给出了一条'a' is out of scope错误消息:

function b() {
    'use strict';
    a();
}

function a() {
    'use strict';
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

这是设计的吗?我应该关心吗?如何在更大(更复杂)的情况下避免这种情况,在这种情况下,可能无法始终为函数提供明确的顺序?

Jua*_*des 4

JSLint/JSHint 希望您在引用函数之前定义它们。然而,JavaScript 并不关心,因为函数和变量都是提升的

您可以更改代码样式,或使用http://jshint.com/docs/options/#latedef告诉 linter 忽略它

/* jshint latedef:nofunc */
function b() {
    'use strict';
    a();
}

function a() {
    'use strict';
    return 1;
}
Run Code Online (Sandbox Code Playgroud)

请参阅/sf/answers/1674170361/

  • 嗯。它现在在 jslint.com 上不起作用,而且我在 [说明](http://jslint.com/help.html) 中也没有看到它。现在,去年 Crockford 更新到 ES6 时,JSLint 发生了很大变化,但我[在旧说明中没有看到这一点](https://web.archive.org/web/20140312234140/http://www.jslint.com /lint.html)(我检查了一些日期),作为[一些评论](http://stackoverflow.com/questions/806163/jslint-using-a-function-before-its-defined-error/9512299# comment19095210_9512299)有建议。也许它是一个奇怪的(*qua*奇怪和罕见的)版本,或者这个答案是错误发布的。 (3认同)
  • 值得注意的是 `latedef:nofunc` 是一个仅 JSHint 的指令。 (2认同)