我编写了具有如下布局的 JavaScript 代码:
function MyObject() {
this.doSomething(){
someSubRoutine();
}
function someSubRoutine(){
//Sub-routine code here
}
}
ReSharper 警告我
Function 'someSubRoutine' is used before it is declared
确实函数在声明之前就已使用,但 ReSharper 建议我在使用之前声明我的函数是否有实际原因?我认为由于 JavaScript 的提升能力,这不会成为问题。我应该遵循此建议还是继续忽略它?
最佳答案
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();
关于javascript - 为什么 ReSharper 在函数声明之前警告它已被使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31141410/