質問

Passing this code through jsHint:

var A = function (spec) { 
  "use strict";
  var a = function () {
    return b();
  };

  var b = function () {
    return 5;
  };

  a();
};

returns this error:

Line 4: return b();
'b' is not defined.

I understand this might have to do with "hoisting" as explained here: JavaScript function order: why does it matter?

However, the following code returns the same error:

var A = function (spec) { 
  "use strict";
  function a () {
    return b();
  }

  function b () {
    return 5;
  }

  a();
};

If I understand correctly, at least the second code snippet should not return an error. Am I mistaken?

Even considering the hoisting mechanism, I still do not understand why the first code snippet should be wrong. Function a is only called after function b is defined, so b would be in a's closure. Is my code wrong or is jsHint wrong?

I understand that this question is purely academic, because the code works as expected in all browser. Nevertheless, I'd like to know why jsHint throws an error.

役に立ちましたか?

解決

This is a false positive in jsLint.
Both of your code snippets work fine.

Ignore the warning.

他のヒント

The first example is a hoisting problem because a() references b() before it's declared. The solution is to have 'var a, b;' after your "use strict"; statement.

jsHint is trying to help you by pointing out potential problems and non-conventional code.

In this case, it's not happy because it might be difficult for a human to understand -- even though it's perfectly valid Javascript.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top