0

我有这样的代码:

function dialog($link) {
    "use strict";

   function doDialogAjax() {
        $.ajax({
            cache: false,
            url: url,
            dataType: 'html'
        })
            .done(onDialogDone)
            .fail(onDialogFail);
   }

   function onDialogDone(data) {
        content = data;
   // ... 
   }
}

jslint 抱怨 onDialogDone 尚未定义。我真的需要在我的代码顶部将它定义为全局吗?我问的原因是因为我不认为 onDialogDone 函数是全局的。它只是一个尚未在外部函数中定义的函数。

我是否正确地说以这种方式定义的函数在最后一个花括号之后的末尾不应有分号?

4

3 回答 3

0

You don't need to define it as a global, just define it before the ajax call. Which in fact doesn't matter for two reasons:

  • the function definition is hoisted anyway
  • the ajax call is asynchronous so the code below will execute before the callback is fired

Nevertheless, it's good to have jslint-compliant code but it's not a matter of life and death ;)

于 2012-09-26T10:52:12.200 回答
0

Your code is perfectly fine. However, since JSLint uses a Pratt Parser (Top Down Operator Precedence) to analyze your code, when it sees onDialogDone for the first time, it complains because it was not defined yet.

To prevent it from complaining, just move the function to the top. This way, JSLint will parse the definition first, and when it sees .done(onDialogDone), it will know what the symbol onDialogDone refers to.

function onDialogDone(data) {
  // ...
}

function doDialogAjax() {
  // ...
}
于 2012-09-26T10:52:50.720 回答
0

jslint抱怨很多事情是因为它的作者认为它们是糟糕的风格,而不是因为它们本质上是不正确的。

在这种情况下,您的函数定义将被提升到范围的顶部,并且是完全有效的代码。

在分号问题上,包含一个并没有什么坏处。不过,ES5 规范并不要求它。

于 2012-09-26T10:50:24.730 回答