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

前端 未结 2 1448
有刺的猬
有刺的猬 2021-01-18 07:02

JSLint seems to be picky about function ordering.

This passes fine:

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

function b() {
    \'use stri         


        
2条回答
  •  不思量自难忘°
    2021-01-18 07:54

    @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.

提交回复
热议问题