为什么在当前作用域内Javascript中声明的变量是不可配置的? [英] Why declared variables in Javascript are non-configurable in the current scope?

查看:58
本文介绍了为什么在当前作用域内Javascript中声明的变量是不可配置的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我用关键字 var 创建了变量 x ,但是当我执行以下操作时:

I have created a variable x with the keyword var but when I do the following:

var x = 10;
delete x;

它返回 false .基本上,我不想删除x变量,但我的问题是,为什么javascript不允许配置在当前作用域上下文中声明的变量.在本文档中,但问题是为什么?

It returns false. basically, I don't want to delete the x variable but my question is that why javascript does not allow to configure the variables declared in the current scope context. This is also mentioned in this documentation, but the question is why?

推荐答案

否则,每个 x 可能会或可能不会抛出错误,或者可能会突然引用另一个变量:

Because otherwise every x might or might not throw an error or might suddenly refer to another variable:

  let x = 2;
  {
     let x = 3;
     if(Math.random() > 0.5) delete x;
     console.log(x); // ?!
  }

这使得代码完全容易出错且难以预测,并且无法进行优化,每一行可能突然变成语法错误,这就是为什么无法以这种方式删除变量的原因.

That makes code conpletely error prone and unpredictable and makes it impossible to optimize, every line might suddenly become a syntax error, and thats why it is not possible to delete variables that way.

但是,还有另一种方法可以通过将对象添加为可以突变的范围来获得此行为,这就是为什么没人使用 with 语句的原因:

However there is another way to get this behaviour by adding an object as scope which you can mutate, and thats the reason why no one uses the with statement:

  const scope = { b: 2 };
  with(scope) {
    console.log(b); // 2
    delete scope.b;
    console.log(b); // reference error
  }

这篇关于为什么在当前作用域内Javascript中声明的变量是不可配置的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆