在本地范围中,未定义为有效变量名称



我已经对声明一个称为 undefined的变量并评估了使用它的真相。我发现在全球范围中不可能。但是在MDN中,我发现了一些有关undefined数据类型的有趣见解。我直接引用MDN

未定义是全局对象的属性;即,它是一个变量 在全球范围中。

它没有对本地范围说任何话。这意味着我可以在本地范围中创建一个。因此,我继续将这种见解进行测试。我创建了一个对象并将方法分配给它

var person = {
   method : function(){
       var undefined = 2
       if(undefined){
          console.log("undefined works as a variable")
       }
   }
}
person.method()

猜猜什么!IF语句通过测试,console.log()内部的字符串被打印在控制台上。这可能是一件危险的事情,当然是不良的做法。有什么方法可以防止以JavaScript的本地范围中的undefined关键字命名的变量声明?谢谢!

要解决undefined的意外修改,您不应该在代码中写下此危险单词。

由于您只需要阅读访问undefined,因此建议将始终使用使用void 0,返回undefined

var person = {
   method: function() {
       var undefined = 2
       if(void 0) {
          console.log("this should never be printed")
       } else {
          console.log("void 0 is always undefined, no matter what you do")
       }
   }
}
person.method()

如何与void 0一起工作并完全摆脱"未定义"一词?

// Turn
if(myVariable === undefined) { ... }
if(typeof myVariable === "undefined") { ... }
// into
if(myVariable === void 0) { ... }
// Turn
if((myVariable === undefined) || (myVariable === null)) { ... }
// into
if(myVariable == null) { ... }
// Turn
myObject.someKey = undefined
// into
myObject.someKey = void 0

欢迎来到JavaScript的美好世界!

没有办法阻止某人这样做,但是有一种方法可以确保undefined表示undefined如果您设置了如下的功能(不是您应该真正必须这样做,因为这将是非常糟糕的练习任何人实际设置一个名为undefined的变量)。本质上,较小的示波器功能可以隐藏更高的示波器undefined变量。

// This is just a way to get a variable called "undefined"
function wrapper(){
  var undefined = 10;
  console.log("wrapper says undefined is: " + undefined);
  // This function declared a parameter called "undefined",
  // but if the function gets called with no argument, then
  // the value of this, more local, argument will truly be
  // undefined. If arguments are needed, just add "undefined" 
  // to the end of the list.
  function foo(undefined){
    // Formal test to ensure that undefined is what we believe it to be:
    if(typeof undefined === "undefined"){
      console.log("foo says undefined is: " + undefined);
    }
  }
  
  // When foo is called with no arguments passed in, the parameter
  // "undefined" will take on a value of undefined within the scope
  // of that function.
  foo();
}
wrapper();

现在,这有点人为,因为您不会使用"假"参数设置所有功能,但是您可以测试以查看undefined是否已更改:

function wrapper(){
  var undefined = 10;
  console.log(undefined);
  
  function foo(){
  
    if(typeof undefined === "undefined"){
       // undefined has not been altered
    } else {
       // undefined has been altered, so reset it for this scope:
       let undefined;
       console.log(undefined);
    }
 
  }
  
  foo();
}
wrapper();

最后,您可以通过在功能中添加var undefined来阻止它影响您的功能。吊装将确保无论您在何处声明它都可以在功能的顶部发挥作用。

我看不到任何停止它的方法,但是是的,如果您可以使用ES6进行本地范围,则可以将其传递给内部。

您将发现范围如果现在更改,那不是同一件事。

var person = {
   method : function(){
   let undefined = 2
   if(undefined){
      console.log("undefined works as a variable")
   }
   }
}

最新更新