函数在定义之前使用 - JSLint

Evg*_*eny 12 javascript jslint

JSLint不喜欢这段代码说''b'在定义之前就被使用了"

var a = function () {
        b();
    },

    b = function () {
        alert("Hello, world!");
    };

a();   
Run Code Online (Sandbox Code Playgroud)

但对此非常满意

var a, b;

a = function () {
    b();
};

b = function () {
    alert("Hello, world!");
};

a();   
Run Code Online (Sandbox Code Playgroud)

但我没有在我的第二个代码片段中定义任何内容.我只是声明变量b.

那么为什么JSLint这样做呢?我有理由先宣布我的所有职能吗?

PS我明白我可以改变a和b的顺序,但在实际项目中我的函数是事件处理程序,有时它们互相调用,所以它可能是不可能的.

Mic*_*ing 12

如果您的代码编写良好且面向对象,则可以在使用之前声明您的函数.但是JSLint设置了许多与应用程序功能关系不大的标准,我真的怀疑是否有任何性能影响以某种方式声明函数.


use*_*123 11

那么为什么JSLint这样做呢?我有理由先宣布我的所有职能吗?

是的,否则可能会出现一些意外错误.您的代码因JavaScript的"吊装"而起作用.此机制会提取隐式或显式的所有声明,并可能导致一些意外结果.

考虑以下代码:

var s = "hello";    // global variable
function foo() {
    document.write(s);   // writes "undefined" - not "hello"
    var s = "test";      // initialize 's'
    document.write(s);   // writes "test"
};
foo();
Run Code Online (Sandbox Code Playgroud)

它被解释如下:

var s = "hello";    // global variable
function foo() {
    var s;               // Hoisting of s, the globally defined s gets hidden
    document.write(s);   // writes "undefined" - now you see why
    s = "test";          // assignment
    document.write(s);   // writes "test"
}
foo();
Run Code Online (Sandbox Code Playgroud)

(例子来自德语维基百科页面:http://de.wikipedia.org/wiki/Hoisting)