About Delete and object replication

Source: Internet
Author: User

This code farming practice, the opening nonsense a few words ...

The day before yesterday's niche was abused ...

No way, as a senior code user, I use the ability of the code, solve the problem of the ability to ask is not weak ...

But its own front-end basis to tell the truth or not perfect, the most obvious manifestation is that the JS core research done relatively little.

The other is the concept is very fragile (PS: My habit is to use a popular metaphor to understand the technology, those boring concepts can not remember a few)

Reality is still as cruel as ever, and many of the little points of knowledge used in peacetime are often used as indicators to reflect a person's ability.

In fact, it is reasonable, after all, it is not justified to use less to study.

OK, the crap is over, start to the chase.

About Delete

Here are a few examples, if you want to use the developer tools to debug, when testing different examples of the trouble to refresh the page, or else may be due to the use of the same variable and problems.

First of all, a simple example (in fact, I did not use the delete at work at all, so once asked this, nine out of ten is going to kneel ...) )

var x = {a:1}; Delete // true // Undefined (Delete object property succeeded)

And then try to delete the variable

var x = 1; Delete // false; // 1 (Failed to delete the variable)

Try deleting a function and see ...

 //  First try this, just declare a function  function   X () {};  delete  x; //  typeof  x; //  function (delete function failed)  //  Try this again, declare a variable, and assign an anonymous function to it  var  y = function   () {};  delete  y; //  typeof  y; //  function (delete function failed)  

Below, let me ruin your three views ...

function  () {}; Delete // true typeof Z;//  undefined (delete succeeded ...)

Why is it possible to delete it this time? If they are all executed under the global context, then they are all properties of the Window object, why is the above example deleted successfully?

The reason is that the example above is actually equivalent to executing the following code

function  assigns a value to the property, not the definition of delete//  truetypeof Z; undefined (delete succeeded ...)

If a variable is not declared with Var, then JS will change the variable into a property of the Window object and then assign a value to the property.

Since this process is not visible to the developer, it is called an implicit attribute assignment. Of course you can also explicitly add a property to the Window object and assign it a value, the result is the same.

This type of explicit/implicit assignment can be deleted with delete.

The above example is in the global environment, below we will transfer the battlefield to the local environment, the interior of the anonymous function.

(function () {   This. x = 1;//Explicit attribute Assignment  vary = 2;//declaring a local variablez = 3;//Implicit property assignment, which becomes a property of the Window object  Delete  This. x;//true  DeleteX//false  DeleteZ//trueConsole.info ( This. x);//undefined (delete succeeded)Console.info (y);//2 (delete failed)Console.info (WINDOW.Z);//undefined (delete succeeded)})()

As you can see, the results are similar in the global context.

We move the environment to a more brutal battlefield--eval

// Please note that before testing a new piece of code, be careful to refresh the next page of eval (' function X () {} '); typeof // function Delete // true; typeof // undefined (delete succeeded)

And then I'm going to ruin your third view ...

// before you test a new piece of code, notice that the page is refreshed, and then no longer prompted ... var x = 1; eval (' function X () {} '); typeof // function Delete // false; typeof // function (delete failed!) )

Why is that? Even if you look at this example again

// declare a variable with the same name after Eval, and also delete the failed eval (' function X () {} '); var x = 1; typeof // function Delete // false; typeof // function (delete failed!) )

First, it is clear here that the variables or functions of the code declaration in eval can be deleted by using Delete.

The variable or function that the code declares in eval, if it has been declared externally (not just the above of Eval, but also includes the following eval), will be re-assigned to the variable, since the invocation of the code in eval is always followed by other variables and function declarations in its outer context.

In this way, the variable is already present, rather than executing the eval-passed code declaration.

So the above example fails to delete because the code declared in eval is not deleted, but the variable is not in the eval code.

OK, and finally a more than shallow summary (the reason is shallow summary, because there are still some cases here is not listed, but that too deep, if you are interested to study, but if not necessary, I think it's OK ... It's tiring to remember those things ... )

1. Display/Implicit object property assignment, which can be deleted by using delete

2. In general, variables and functions declared in the code cannot be deleted through delete

3. Variables and functions that pass through the code declaration through the Eval function can be deleted through delete, provided that the variable was not declared in the external context before

Finally, if you want to do a more in-depth study of the delete, and want to find the principle, here is a very good and professional article:http://justjavac.com/javascript/2013/04/04/ Understanding-delete-in-javascript.html

About Object replication

Since the object is a reference type, it cannot be done with regular assignment when we respond to cloning an object.

// The following code actually just lets two different variables refer to the same object var a = {  ' Jack ',  ' Male '}; var b = A;

If you want to copy the object, it should be the right thing to do.

var a = {  ' Jack ',  ' Male '}; var b = {};  for (var in a) {  = A[key];}

But... Is that enough for you? What if a property of an object is another object, or an array?

In this way, it involves shallow copying and deep copying of objects.

The above approach, only to achieve shallow copy of the object, for the deep copy, we have to use the following method to complete.

//declaring an object clone functionfunctionClone (obj) {varresult = {}; var_clone =function(Objo, OBJC) { for(varKeyinchobjo) {      varCurproperty =Objo[key]; if(Curproperty.constructor = =Array) {        //when the value of a property is an array ...Objc[key] = [];  for(vari = 0, len = curproperty.length; i < Len; i++) {Objc[key].push (curproperty[i]); }      } Else if(Curproperty.constructor = =Object) {        //when the value of the property is an object ...Objc[key] = {};      _clone (Curproperty, Objc[key]); } Else {        //Other cases ...Objc[key] =Objo[key];  }    }  };  _clone (obj, result); returnresult;}//test ...varA ={name:' Jack ', love: [' Lily ', ' Kate ', ' Lucy '], fav: {color: [' Red ', ' black '], sport:' Football '}, Eat:function() {alert (' Fuck you! ')  }};varb = Clone (a);

About Delete and object replication

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.