This time I will bring you a detailed explanation of javaScript objects, what are the precautions for using javaScript objects, the following is a practical case, let’s take a look.
1. Objects are passed by reference, they are never copied.
var x={};var stooge=x; stooge['a']='aaa';console.log(x.a);//aaa
2. You can achieve the copying effect by adding a create method to Object to create a new object with the original object as its prototype. That is, changing the value of a new object will not affect the prototype of that object.
if(typeof Object.beget!=='function'){Object.create=function(o){var F=function(){}; F.prototype=o;return new F(); } }var another_stooge=Object.create(stooge);
typeof is used to determine the type of object. (It will check the prototype chain)
hasOwnProperty method will not check the prototype chain.
4. for in can be used to traverse all property names in an object, but properties including functions and prototype chains will also be traversed. In this case, you can use typeof or hasOwnProperty to exclude the values you do not want.
var name;for(name in another_stooge){if(typeof another_stooge[name] !=='function'){ console.log(name+':'+another_stooge[name]) } }
But the order in which the for in method attributes appear is uncertain.
for loop is OK.
It is recommended to use an array to store variable values, and then use a for loop to traverse. (But I personally feel that you don’t know what key values are in the object, so for in is still necessary.)
var arr=['a','b','c'];for(var i=0;i<arr.length;i++){console.log(arr[i]+':'+another_stooge[arr[i]]); }
5.deleteOperator can be used to delete objects Property, if the object contains the property, then the property will be removed, it will not touch any object in the prototype chain.
Deleting an object's properties may reveal properties in the prototype chain.
6. Reduce global variable pollution. One way to minimize the use of global variables is to create only one unique global variable for your application. Place other variables or functions under this global variable.
var MyApp={}; MyApp.stooge={'first-name:'aaa' }; MyApp.flight=function(){}
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
Detailed explanation of css3 shadow
JavaScript array usage collection
Knowledge points of javaScript that are easily overlooked
How to use canvas to draw the starry sky, the moon, the earth, and add text
The above is the detailed content of Detailed explanation of javaScript objects. For more information, please follow other related articles on the PHP Chinese website!