为什么在Javascript5严格模式下不允许删除?

sir*_*lot 49 javascript ecmascript-5 strict-mode

我对javascript很新,但我很喜欢它的危险快速和松散的表现力.也就是说,我注意到显然在"使用严格"模式下操作时,您无法删除对象.我不是一个删除东西的忠实粉丝(因为从理论上讲,范围应该照顾到这一点),但我想知道删除这个功能背后的动机是什么?

Poi*_*nty 73

delete语句仍然允许在严格模式下,但它的某些特定用途是错误的.它仅允许对象属性,而不是简单名称,并且仅允许可以删除的对象属性.

从而

var a = {x: 0};
delete a.x;
Run Code Online (Sandbox Code Playgroud)

很好,但是

delete Object.prototype;
Run Code Online (Sandbox Code Playgroud)

不是,也不是

delete a;
Run Code Online (Sandbox Code Playgroud)

(后者实际上是语法级错误,而尝试删除不可删除属性是运行时错误.)

  • @sircodesalot:不允许变量绑定在范围内更改.如果范围包含`var foo`,则该范围内对`foo`的所有引用都将引用为该范围创建的变量.否则,它们将引用外部作用域中的变量`foo`(如果存在).由于变量不是由可执行语句创建的,因此它们也不能被销毁. (11认同)
  • 有趣.那么为什么禁止能够删除实际的var本身呢? (5认同)
  • @sircodesalot因为让一个局部变量消失是非常奇怪的.它使得代码块的语义更难描述.(我真的不确定我是否看到过"官方"理由.) (2认同)
  • window.a似乎适用于全局的情况.这是一个有用的替代品吗? (2认同)

Ami*_*hah 6

[删除] 详细解释举例

// The delete statement is still allowed in strict mode, but some particular uses of it are erroneous. It's only allowed for object properties, not simple names, and only for object properties that can be deleted.

// "use strict";

// creates the property adminName on the global scope
adminName = "xyz";

// creates the property empCount on the global scope
// Since we are using var, this is marked as non-configurable. The same is true of let and const.
var empCount = 43;

EmployeeDetails = {
  name: "xyz",
  age: 5,
  designation: "Developer"
};

// adminName is a property of the global scope.
// It can be deleted since it is created without var.
// Therefore, it is configurable.
console.log("delete adminName =", delete adminName); // returns true

// On the contrary, empCount is not configurable,
// since var was used.
console.log("delete empCount =", delete empCount); // returns false

// delete can be used to remove properties from objects
console.log("delete EmployeeDetails.name =", delete EmployeeDetails.name); // returns true

// Even when the property does not exists, it returns "true"
console.log("delete EmployeeDetails.salary =", delete EmployeeDetails.salary); // returns true

// delete does not affect built-in static properties
console.log("delete Math.PI =", delete Math.PI); // returns false

// EmployeeDetails is a property of the global scope.
// Since it defined without "var", it is marked configurable
console.log("delete EmployeeDetails =", delete EmployeeDetails); // returns true

x = 1;
var y = 2;

function f() {
  var z = 44;

  console.log("delete x =", delete x); // returns true
  console.log("delete y =", delete y); // returns false
  // delete doesn't affect local variable names
  console.log("delete z =", delete z); // returns false
}

f.call();
Run Code Online (Sandbox Code Playgroud)