1. Variables
Speaking of the delete operator in JavaScript, we must first understand the relationship between variables and attributes in JavaScript.
In JavaScript, the relationship between variables and object properties is very subtle, and they can even be equated in many cases, because JavaScript will create a global object before executing the script, which is the window object in the browser, and all global variables are this Attributes of the global object. When executing a function, an activation object will also be created. All local variables are attributes of this activation object. You can learn about these javascript scopes and closures.
It seems that variables are equivalent to object properties, but this is not the case, at least for the delete operator. My understanding is that variable declaration must be completed through the var statement. Global variables not declared through the var statement are all attributes of the window object. This makes it easy to understand the relationship between variables and object properties.
2. delete operator
The delete operator is used to delete object attributes. For reference type values, it also deletes the object attribute itself and does not delete the object pointed to by the attribute. If you have any questions, you can look at the values of basic types and reference types, or test the following code:
In addition, delete o.x can also be written as delete o["x"], both of which have the same effect.
3. Variables cannot be deleted
Variables declared through var and functions declared through function have the dontdelete attribute and cannot be deleted. Global variables (properties of global objects) not declared through var
4. The attributes declared in the prototype and the attributes of the object cannot be deleted
The attributes declared in the prototype prototype and the attributes that come with the object (in fact, these attributes are also in the prototype prototype) can be considered to have the dontdelete feature and cannot be deleted. For example,
5. Several exceptions under the eval statement
In the code executed byeval, although variables declared with var belong to the same global object as normal var-declared variables, they do not have the dontdelete feature and can be deleted. However, variables defined through var within the function in the eval code have dontdelete and cannot be deleted.
6. Return value of delete
delete is a normal operator and will return true or false. Returns false when the property of the deleted object exists and has dontdelete, otherwise it returns true. One feature here is that true is returned even when the object attribute does not exist, so the return value is not completely equivalent to whether the deletion is successful or not.