简体   繁体   English

我可以防止意外覆盖TypeScript / JavaScript中的局部变量吗?

[英]Can I prevent accidental overwrite of local variables in TypeScript / JavaScript?

Today I wasted an hour debugging a trivial issue, where a local variable named server was being initialized and configured - then, on one of the last lines in the same file, accidentally it was being redeclared, eg by another var server = ... statement, effectively creating a new variable named server , thus causing the previous variable to fall out of scope; 今天我浪费了一个小时来调试一个简单的问题,其中一个名为server的局部变量正在初始化和配置 - 然后,在同一文件的最后一行中,意外地重新声明它,例如由另一个var server = ...声明,有效地创建一个名为server变量,从而导致前一个变量超出范围; yet, because these were the same type of variable, with the same name, everything else continued to work, making this fairly hard to debug. 然而,因为这些是相同类型的变量,具有相同的名称,所以其他一切继续工作,这使得调试相当困难。

Is there a TypeScript or JavaScript language feature, that prevents this sort of thing? 是否有TypeScript或JavaScript语言功能,可以防止这种情况?

My thinking is that, declaring two variables with the same name, in the same scope, ought not to be allowed at all. 我的想法是,在同一范围内声明两个具有相同名称的变量,根本不应该被允许。

Perhaps there's a linter or some quality assurance tool that has the ability to check for and prevent this sort of thing? 也许有一个短绒或一些质量保证工具,有能力检查和防止这种事情? (and perhaps other "bad" patterns?) (也许还有其他“坏”模式?)

Use let everywhere possible. 尽可能使用let

A let variable cannot be used before its declaration: 在声明声明之前不能使用let变量:

var x = 3;
function f() {
  console.log(x); // ReferenceError, x is not defined
  let x = 5;
}

Two options: 两种选择:

  1. Use ECMA Script 6 and let . 使用ECMA Script 6并let
  2. Use jslint with var . 使用带有var jslint

There is a closed issue about this on the GitHub/Microsoft/Typescript page. 在GitHub / Microsoft / Typescript页面上有一个关于此的已关闭问题 The recommendation is to target ECMA Script 6 and use let . 建议是以ECMA Script 6为目标并使用let

ECMA Script 6 with let ECMA Script 6 with let

In ECMA Script 6 this would create an error : 在ECMA Script 6中,这会产生错误

let x = "foo";
let x = "bar"; // TypeScript with ECMA 6 will complain here
console.log(x);

Duplicate declaration, x 重复声明,x

JSLint with var 带有var JSLint

Also, though the following won't throw a TypeScript error , the jslint tool will complain about it, even if you aren't using strict. 此外, 虽然以下内容不会引发TypeScript错误 ,但即使您没有使用strict, jslint工具也会抱怨它。

(function () {

    var x, y;
    x = "foo";
    y = "foo";

    function sayMsg() {
        // jslint will complain here
        var y = "bar";
    }

    sayMsg();

    // jslint will also complain here
    var x = "bar" + y;

}());

This is what jslint will tell you: 这就是jslint会告诉你的:

Redefinition of 'y' from line 3. 从第3行重新定义'y'。

Combine this with the previous 'var' statement. 将其与之前的'var'语句相结合。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM