是否有 ESLint 规则可以捕获以下内容?
const foo = () => 1
const bar = () => {
const foo = foo() // 1. identifier 'foo' is set to undefined in this context 2. invoking foo() results in an error since `foo` is undefined
return foo
}
> bar()
> Uncaught ReferenceError: foo is not defined
at bar (<anonymous>:4:15)
at <anonymous>:1:1
换句话说,当一个 const 被赋予它自己的值时,我想得到一个 linter 错误。
最佳答案
据我所知,与您的用例最接近的规则是 ESLint 的 no-use-before-define
。它会将此视为在 const foo
之前使用 foo
并且它会出错。
唯一的缺点是这条规则没有做完整的代码流分析,所以对于像这样的情况它也会出错
var getFoo = () => foo;
const foo = 4;
getFoo();
因为它仍然看到 foo
在 const foo
之前使用,即使在运行时它只在之后使用。如果您的代码库不这样做或可以修复,这可能不是问题,但如果您要将规则添加到现有的大型代码库,这可能会很烦人。
关于javascript - ESLint 规则通过创建同名的 const 来防止覆盖函数(尤其是在赋值期间),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42538058/