Introduction to delete in Javascript _ javascript tips-js tutorial

Source: Internet
Author: User
Tags chrome developer
The Delete in JavaScript has not been clearly understood. I have recently seen two articles in this regard. I am now translating some of the content in the two articles (the content has been modified and added, and the order is not exactly the same, if you are interested in reading the original article), I hope it will help you. I. Question proposal

Let's take a look at the following code. Note that the following code should not run in browser Developer tools (such as FireBug and Chrome Developer tool). The reason will be explained later:

Why can we delete the attributes of an object:

The Code is as follows:


Var o = {x: 1 };
Delete o. x; // true
O. x; // undefined


But do not delete the variables declared like this:

The Code is as follows:


Var x = 1;
Delete x; // false
X; // 1


You cannot delete a function defined as follows:

The Code is as follows:


Function x (){}
Delete x; // false
Typeof x; // "function"


Note: When the delete operator returns true, the operation can be deleted. If the delete operator returns false, the operation cannot be deleted.

To understand this, we need to first master the concepts such as variable instantiation and attribute features-unfortunately, these contents are rarely mentioned in some javascript books. It is not difficult to understand them. If you don't care why they are running, you can skip this part at will.

Ii. Code Type

There are three types of executable code in ECMAScript: Global code, Function code, and Eval code ).

The Code is as follows:


Var x = 1; // Global code
Function test (){
Var y = 2; // Function Code
Eval ("var z = 3"); // Eval Code in Function
}
Eval ("function evalTest () {}"); // Eval Code in Global



Iii. Execution Context

When ECMAScript code is executed, it always runs in a certain context. The execution context is a somewhat abstract entity, which helps us understand how the scope and variable instantiation work. For three types of executable code, each has an execution context. When a Function is executed, it can be said that the control enters the execution context of the Function code. The Global code Execution context is displayed.

As you can see, the execution context logic comes from a stack. First, there may be a global code with its own scope. The Code may call a function, which has its own scope, and the function can call another function. Even if a function recursively calls itself, each call enters a new execution context.

4. Activation object/Variable object)

Each execution context has a Variable Object within it. Similar to the execution context, Variable object is an abstract entity used to describe the mechanism of Variable instantiation. Interestingly, the variables and functions declared in the Code are actually added as attributes of the variable object.

When the execution context of the global code is entered, a global object is used as a variable object. This is exactly why the variables or functions declared in the global scope become the attributes of the global object.

The Code is as follows:


/* Remember that 'eas' refers to global object when in global scope */
Var GLOBAL_OBJECT = this;

Var foo = 1;
GLOBAL_OBJECT.foo; // 1
Foo = GLOBAL_OBJECT.foo; // true

Function bar (){}
Typeof GLOBAL_OBJECT.bar; // "function"
GLOBAL_OBJECT.bar ==bar; // true


The global variable becomes the attribute of the global object. But what about the local variables defined in the Function code? The behavior is actually very similar: it becomes the property of the variable object. The only difference is that in Function code, variable objects are called Activation objects instead of global objects ). Every time the Function code enters the execution scope, an Activation object is created ).

Not only do variables and functions in Function code become the attributes of the activated object, but also each parameter (name corresponding to the form parameter) of the Function and a specific Arguments object. Note that activating an object is an internal mechanism and will not be accessed by the program code.

The Code is as follows:


(Function (foo ){

Var bar = 2;
Function baz (){}

/*
In abstract terms,

Special 'arguments' object becomes a property of ining function's Activation object:
ACTIVATION_OBJECT.arguments; // Arguments object

... As well as argument 'foo ':
ACTIVATION_OBJECT.foo; // 1

... As well as variable 'bar ':
ACTIVATION_OBJECT.bar; // 2

... As well as function declared locally:
Typeof ACTIVATION_OBJECT.baz; // "function"
*/

}) (1 );


Finally, the variables declared in the Eval code are created as attributes of the variable object in the context of the call. The Eval code only uses the variable object of the execution context in which it is called.

The Code is as follows:


Var GLOBAL_OBJECT = this;

/* 'Foo' is created as a property of calling context Variable object,
Which in this case is a Global object */

Eval ('var foo = 1 ;');
GLOBAL_OBJECT.foo; // 1

(Function (){

/* 'Bar' is created as a property of calling context Variable object,
Which in this case is an Activation object of containing function */

Eval ('var bar = 1 ;');

/*
In abstract terms,
ACTIVATION_OBJECT.bar; // 1
*/

})();


V. Attribute features
Now the variables are clear (they become attributes), and the only concept to be understood is the attribute feature. Each attribute has zero or multiple features from one of the following attributes-ReadOnly, DontEnum, DontDelete, and Internal. You can think of them as a tag and an attribute as dispensable. For the purpose of today's discussion, we only care about the DontDelete feature.

When declared variables and functions become attributes of a variable object, they are either Function code or Global code. These created attributes have the DontDelete feature. However, any explicitly (or implicitly) created attribute does not have the DontDelete feature. This is why some of our attributes can be deleted, and some cannot.

The Code is as follows:


Var GLOBAL_OBJECT = this;

/* 'Foo' is a property of a Global object.
It is created via variable declaration and so has DontDelete attribute.
This is why it can not be deleted .*/

Var foo = 1;
Delete foo; // false
Typeof foo; // "number"

/* 'Bar' is a property of a Global object.
It is created via function declaration and so has DontDelete attribute.
This is why it can not be deleted either .*/

Function bar (){}
Delete bar; // false
Typeof bar; // "function"

/* 'Baz' is also a property of a Global object.
However, it is created via property assignment and so has no DontDelete attribute.
This is why it can be deleted .*/

GLOBAL_OBJECT.baz = 'blah ';
Delete GLOBAL_OBJECT.baz; // true
Typeof GLOBAL_OBJECT.baz; // "undefined"



Vi. built-in attributes and DontDelete

In a word, a unique attribute (DontDelete) controls whether this attribute can be deleted. Note that the built-in attributes of an object (that is, the predefined attributes of an object) have the DontDelete feature, so they cannot be deleted. For specific Arguments variables (or, as we know now, activating object attributes), The length attribute of any function instance also has the DontDelete feature.

The Code is as follows:


(Function (){

/* Can't delete 'arguments ', since it has DontDelete */

Delete arguments; // false
Typeof arguments; // "object"

/* Can't delete function's 'length'; it also has DontDelete */

Function f (){}
Delete f. length; // false
Typeof f. length; // "number"

})();


The created attributes corresponding to function parameters also have the DontDelete feature, so they cannot be deleted.

The Code is as follows:


(Function (foo, bar ){

Delete foo; // false
Foo; // 1

Delete bar; // false
Bar; // 'blah'

}) (1, 'blah ');



7. Undeclared assignment

Simply put, an undeclared value is used to create a deletable attribute on a global object.

The Code is as follows:


Var GLOBAL_OBJECT = this;

/* Create global property via variable declaration; property has DontDelete */
Var foo = 1;

/* Create global property via undeclared assignment; property has no DontDelete */
Bar = 2; // it can be understood as window. bar = 2; it can be deleted according to the fifth point above.

Delete foo; // false
Typeof foo; // "number"

Delete bar; // true
Typeof bar; // "undefined"


Please note that the DontDelete feature is determined during the attribute creation process, and the subsequent assignment will not modify the existing attributes, so it is important to understand this.

The Code is as follows:


/* 'Foo' is created as a property with DontDelete */
Function foo (){}

/* Later assignments do not modify attributes. DontDelete is still there! */
Foo = 1;
Delete foo; // false
Typeof foo; // "number"

/* But assigning to a property that doesn't exist,
Creates that property with empty attributes (and so without DontDelete )*/

This. bar = 1;
Delete bar; // true
Typeof bar; // "undefined"


VIII. Eval code
Variables or methods created in Eval are special. They do not have the DontDelete feature, that is, they can be deleted.

The Code is as follows:


Eval ("var x = 1 ;");
Console. log (x); // 1
Delete x;
Console. log (typeof x); // undefined

Eval ("function test () {var x = 1; console. log (delete x);/* false */; return 1 ;}");
Console. log (test (); // 1
Delete test;
Console. log (typeof test); // undefined


Note: The variables or methods created in Eval do not include the variables or methods in the method. For example, the red part in the code above is still consistent with the previous description: they cannot be deleted.

9. FireBug confusions

Let's take a look at the code execution results in FireBug:

The Code is as follows:


Var x = 1;
Delete x;
Console. log (typeof x); // undefined

Function y (){
Var z = 1;
Console. log (delete z); // false
}
Y ();
Delete y;
Console. log (typeof y); // undefined


This clearly violates the above rules, but compared with the above eight points, we found that this is the effect of code execution in eval. Although not confirmed, I guess the console code in FireBug (Chrome Developer tool) is executed using eval.

Therefore, when testing JavaScript code, pay special attention to the current context.

10. Objects deleted by the delete Operator

C ++ also has the delete operator, which deletes the object pointed to by the pointer. For example:

The Code is as follows:


Class Object {
Public:
Object * x;
}

Object o;
O. x = new Object ();
Delete o. x; // The new Object in the previous row will be released.


However, unlike C ++, Javascript delete does not delete the objects pointed to by o. x, but deletes the o. x attribute itself.

The Code is as follows:


Var o = {};
O. x = new Object ();
Delete o. x; // The new Object in the previous Row still exists.
O. x; // undefined. The attribute named x of o is deleted.


In actual Javascript, delete o. after x, the Object will be reclaimed due to the loss of reference, So delete o. x is equivalent to deleting o. x points to the Object, but this action is not the ECMAScript standard. That is to say, even if an implementation does not delete the Object at all, it is not in violation of the ECMAScript standard.

You can use the following code to confirm "delete attributes rather than objects.

The Code is as follows:


Var o = {};
Var a = {x: 10 };
O. a =;
Delete o. a; // The o. a attribute is deleted.
O. a; // undefined
A. x; // 10, because the {x: 10} object is still referenced by a, it will not be recycled.


In addition, delete o. x can also write delete o ["x"], with the same effect.

11. Other attributes that cannot be deleted

Except for the built-in attributes (pre-defined attributes) mentioned above, the attributes declared in prototype cannot be deleted:

The Code is as follows:


Function C () {this. x = 42 ;}
C. prototype. x = 12;
C. prototype. y = 13;

Var o = new C ();
O. x; // 42, the o. x defined in the constructor

Delete o. x; // true deletes the custom x
O. x; // 12. o. x defined in prototype will not be deleted even if delete o. x is executed again.

Delete o. y; // true, because o itself does not have the o. y attribute, and y exists in the prototype chain, that is, the object's attributes are different from those of prototype.
O. y; // 13



Summary

As mentioned above, I hope to help you understand Delete In JavaScript. Due to the limited level, it is not guaranteed to be completely correct. If any error is found, please correct it.

Original:
1. http://perfectionkills.com/understanding-delete)
2. http://nanto.asablo.jp/blog/2008/01/09/2552470 (Japanese)

First http://jscode.cnblogs.com
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.