JSLint “out of scope” error due to function ordering?

 ̄綄美尐妖づ 提交于 2019-12-19 18:57:10

问题


JSLint seems to be picky about function ordering.

This passes fine:

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

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

While this gives an 'a' is out of scope error message:

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

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

Is this by design? Should I care? How can it be avoided in larger (more complex) cases, where it might not always be possible to give the functions a clear order?


回答1:


JSLint/JSHint expect you to define functions before you reference them. However, JavaScript doesn't care because functions and variables are hoisted.

You can change your code style, or tell the linter to ignore it using http://jshint.com/docs/options/#latedef

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

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

See https://stackoverflow.com/a/23916719/227299




回答2:


@epascarello's link to where this was discussed for JSHint really is absolutely essentially here, because this isn't just a question of style.

Let's hit the high points of the excellent answer at that question, as it applies to JSLint as well.*

There are two ways to define functions: Function declaration and function expression. The difference is annoying and minute, so let's just say this slightly wrong thing: If you're writing it like function name() {}, it's a declaration, and when you write it like var name = function() {} (or an anonymous function assigned to a return, things like that), it's a function expression.

bar(); //This won't throw an error
function bar() {}

foo(); //This **WILL** throw an error
var foo = function() {}

[emphasis mine -r]

It really is worth reading all of the answer there, but it's also worth emphasizing that this JSLint error isn't just about style, it's warning you about the possibility of a functional error. Edge-case-y, sure, but a useful habit.

I'll also add that there shouldn't be a case where you have to recursively call functions in JavaScript that exist before they're defined. I've been annoyed when I've seen this error in that context a few times, but it's [almost?] always helpfully shown some code smell where a refactoring was useful rather than a place where all the function jumping is required.

It seems like you might be able to cheat around the warning if you jump a lot with function namespacing, which I may have embarrassingly done in a case or two. I hope not (on both counts), though.


* I was tempted to add JSLint to that question and call this one a dupe, but wasn't sure that was quite kosher.



来源:https://stackoverflow.com/questions/34614490/jslint-out-of-scope-error-due-to-function-ordering

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!