5

我用如下所示的布局编写了 JavaScript 代码:

function MyObject() {
    this.doSomething(){
        someSubRoutine();
    }

    function someSubRoutine(){
        //Sub-routine code here
    }
}

ReSharper 警告我

在声明之前使用函数“someSubRoutine”

确实在声明函数之前使用了该函数,但是 ReSharper 建议我在使用之前声明我的函数是否有实际原因?我认为由于 JavaScript 的提升能力,这不会是一个问题。我应该遵循这个建议还是继续忽略它?

4

1 回答 1

6

ReSharper 可能在后台使用 JSLint(或 JSHint),这些 linting 工具通常会警告这种做法。

该问题归结为一个名为“提升”的主题,该主题已被大量讨论(例如,Sitepoint)。在某些情况下,可以在 JS 解释器有机会声明它之前使用方法或变量......所以“最佳实践”是在第一次使用之上的某个地方声明。

编辑: 这是一个示例,其中提升会导致可能的意外副作用:

var showState = function() {
    console.log("Idle");
};

function showState() {
  console.log("Ready");
} 

showState();            // output: Idle

这是因为 JS 解释器在运行时使用提升来创建以下内容:

function showState(){        // moved to the top (function declaration)
    console.log("Ready");
} 

var showState;               // moved to the top (variable declaration)

showState = function(){      // left in place (variable assignment)
    console.log("Idle");
};

showState();
于 2015-06-30T14:52:41.777 回答