First, the definition of the object:
An object is a basic data type of JavaScript and is a composite value that aggregates many values (primitive values or other objects) together to access them by name. That is, an unordered collection of attributes.
Ii. Creation of objects (multiple methods)
1. Object Direct volume/literal
var obj = { name: ' lyl ', age:18 } console.log (obj.name);//Lyl
2. Constructor:
(1), the system comes with, Eg:new Object (), Array (), number (), Boolean (), Date () ...
var obj = new Object (); Obj.name = ' lyl '; Console.log (Obj.name); Lyl
(2), custom: In order to distinguish with the common function, the first letter capitalized, the use of large hump style (ordinary function using small hump style notation)
function OBJ (name) { this.name = name; This.age =; } var obj = new obj (' lyl '); Console.log (Obj.name); Lyl Console.log (obj.age);//18
The basic construction principle of a custom constructor:
First of all, the text theory explains, in fact, all the key to the new operator, with new and do not return the results of new. Without new, obj (' lyl ') is simply a function of normal execution, no return value, the default is to return to undefined, but with the new operator after the JS engine will see the function as a constructor, after a series of hermit operations, the return value is an object.
Look at the following demo:
Demo1: The difference between new and no new is demonstrated:
function Obj () { this.age =; } no new Console.log (obj ());//undefined // with new console.log (New obj ());//obj {age:18}
Demo2 uses the new return value as the basic principle of the object:
Without new, this in the function points to window, so the variable defined by THIS.XXX is a property on the window, but why is this not a Window object after using new? That's because
With new, the JS engine will perform a two-step hermit operation on the function (assuming the constructor is named person): The first step, var this = object.create (Peson.prototype); (also a way to create an object, as described below) the meaning of this in the change function of a hermit, now the this in the function is a prototype for Person.prototype, the constructor is the object of the person (in fact, this process will want to basically create a successful object, It's just a few attributes, but it's obvious that the fundamental principle of the constructor creation object is to borrow the Object.create () method to implement it, but it is encapsulated and functional); second, after the created object is set to the desired properties, the hermit will create the object this returns by return return this;
Through the display of code:
prototype of the constructor Person.prototype = { say:function () { console.log (' I am saying '); } } constructor Function Person () { // Hermit action //var this = Object.create (person.prototype); Returns the setting of the object property this.name = ' lyl '; This.age =; Hermit operation //return this; } var person1 = new Person (); Console.log (Person1.name); Lyl Person1.say ();//i am saying
Verification of the above two-step theory:
The first step: the This in the function now is a prototype for Person.prototype, the constructor for the person object
prototype of the constructor Person.prototype = { say:function () { console.log (' I am saying '); } } constructor Function Person () { this.name = ' lyl '; This.age =; Prints the prototype of this object Console.log (this.__proto__);///// Verify if this is an instance of the person constructor Console.log (this instanceof person); True } new Person ();//print result as follows // object say: () __proto__: Object /True person ();// Print the result as follows // Window //False
Step two: The hermit will create the object this returns by return
By some of the above code, we can already see that the object that satisfies the condition is returned, and now we create the object without new and show the impersonation of the two-step hermit operation to verify (we do not have a new then two-step hermit operation will not be generated)
prototype of the constructor Person.prototype = { say:function () { console.log (' I am saying '); } } constructor Function Person () { var = object.create (person.prototype); That.name = ' lyl '; That.age =; return that; Returns earlier that causes return this to fail to execute and expires } var person = new person ();
There is no need for new to return an object that satisfies the condition, because the displayed return is that Console.log (person.name);//lyl Person.say ();//i am saying
P.s. With respect to the problem of displaying the return to that, when we use new to generate the object, if we show the return is an object/reference value, it will cause return this to fail, and if the original value is returned, return this will not be invalidated
3, Object.create (prototype); Create an instance object that inherits the prototype
Some considerations for this approach:
(1), if the reference is Object.prototype, the prototype is created as Object.prototype, and the object created by the new object is the same object.create (Object.prototype) < ==>new Object ();
(2), if the argument is empty or null, the created object is not prototype, causing the object to be unable to print with document.write () error, because document.write () The principle of printing is to call the Object.prototype.toString () method, which does not have a prototype, and there is no method, so document.write () cannot print
This extension of knowledge points: Reference values are also counted as objects, so can be printed with document.write (), the original value Numebr, Boolean, string has its own object wrapper class, with this mechanism can also be used with document.write () to print out;
However, undefined and null are neither reference values nor wrapper classes, so they should not be printed, but you will find that the two values are also printed with document.write () because the two values are set to a special value, document.write () Print it without calling any method, but printing its value directly
Third, the object of the increase, deletion, change, search
1, increase: the so-called addition of an object property, is directly assigned to the property operation can be, this is equivalent to adding a new property for the object, and printing the property not added, the browser will not error, but will print out undefined
var obj = {}; Console.log (Obj.name); Undefined (no error) obj.name = ' lyl '; Console.log (Obj.name); Lyl
2. Delete: We remove the properties of an object by using the delete operator
var obj = { name: ' Lyl ' }; Console.log (Obj.name); lyl Delete obj.name; Console.log (Obj.name); Undefined
3, change: Modify the properties of an object is the simplest, directly by assigning the value of its other values can be
var obj = { name: ' Lyl ' }; Console.log (Obj.name); lyl obj.name = ' obj '; Console.log (Obj.name); Obj
4. Check: There are two ways to query the property value of an object
var obj = { name: ' Lyl ' }; The first method Console.log (obj[' name ");//lyl //The second method Console.log (obj.name);//Lyl
P.S. All three operations, such as add, delete, and change, operate on the properties of the current object only, without affecting the properties of the prototype of the current object.
The query first looks at whether the property is set by the current object itself, and if the property is not set by the current object, then whether the property is set in the prototype of the object, and if neither, returns undefined
Four, packaging type:
1, five primitive Values: Number, String, Boolean, Undefined, null
where number, String, and Boolean are respectively own wrapper classes, while undefined and null are not their own wrapper classes
2. The original value is not an object and cannot have its own property, but because of the existence of the wrapper class, the original value seems to have its own property, but its properties are somewhat special, such as the following string for example:
Read a code First
Str is a string type, non-object, cannot have properties, why can I print out str.length? var str = ' ABCD '; Console.log (str.length); 4
Explanation of the problem in the above code:
Because the wrapper class of the type object will wrap the statement after each execution of a complete JS statement, it will not cause an error, which is written by the background of var str = ' ABCD '; var str1 = new String (' ABCD '); Console.log (str.length); 4 // var str1 = new String (' ABCD '); Console.log (str1.length);
Note: Each wrapper class is destroyed after it has finished wrapping a complete statement. (that is, to interpret a statement, wrap it in a wrapper class, and then destroy), which causes some differences between it and the normal object, as in the following example
var str = ' ABCD '; Str.len = 4; Console.log (Str.len); Undefiend
???
The key is the word ' destroy ', which is explained as follows:
var str = ' ABCD '; var str1 = new String (' ABCD '); Destroy Str.len = 4; var str1 = new String (' ABCD '); Str1.len = 4; Destroy Console.log (Str.len);//Undefiend //var str1 = new String (' ABCD '); Console.log (Str.len); STR1 is a newly created object whose Len attribute is naturally undefiend //Destroyed
An easy-to-mistake pit:
In short remember ' raw value wrapper class ' ' destroy ' these two words on the line var str = ' ABCD '; Str.lenth = 2; Console.log (str); AB or ABCD? Answer is ABCD console.log (str.length);//2 or 4? Answer is 4
V. Prototypes:
1. Prototype definition: A prototype is a property of a function object that defines the common ancestor of the object that the constructor produces. By changing the object generated by the constructor, you can inherit the properties and methods of the prototype. Prototypes are also objects.
2, using the prototype features and concepts, you can extract the common attributes. The common properties of a class of objects are extracted and placed in the prototype of the class object, so that the common properties are not redefined every time the new operator is used.
As below, define a person constructor, which belongs to a property method common to the person multi-constructed object, is defined in the prototype of the person
Person.prototype = { eat:function (food) { Console.log (' I had eated ' + food); }, sleep:function () {
console.log ("I am Sleeping"); } } Man's constructor function person (name, age) { this.name = name; This.age = age; } var person1 = new Person (' lyl ', +); Console.log (Person1.name); Lyl person1.eat (' Apple ');//i has eated apple
3. How to view prototypes:
Previously, we were not allowed to view the prototype of the constructor, but later provided an interface to view the constructor prototype: the Hermit attribute __proto__ (in fact, we can access the properties of the prototype, or inherit the prototype, by the __proto__ property is connected to the constructor and prototype, can say no __ Proto__ the existence of a property, it is impossible to implement the inheritance of the prototype)
(1), first of all, we first explain the __proto__ this interface is where to store
If you have seen the above object creation process, you should know that when you create an object with new, the inner hermit automatically creates an object of this, and after a series of processing, the hermit returns the This object. And __proto__ is the following code for the This object created by the hermit:
Prototype Person.prototype = { say:function () { console.log ("I am saying"); }, play:function () { Console.log ("I am Playing"); } } constructor function person (name) { //var this = Object.create (person.prototype); P.s. A property exists in the This object created by the hermit, that is, __proto__, which stores person.prototype this.name = name; return this; } Object Creation var person1 = new Person (' lyl '); Print prototype console.log (person1.__proto__);
(2), how to view the prototype: Access the __proto__ property directly from the object created by the new operator, as shown in the Code demo
4, how to view the object's constructor, we use the property constructor to view:
The Contructor property is in the constructor's prototype, where the constructor information is stored, so, without knowing the prototype, the prototype inherits the principle that we can use the instance object to directly access constructor, that is, to get the constructor that created the instance.
function person () { this.name = ' myName '; This.age =; } var person = new person (); Console.log (Person.constructor); function Perso () {...}
Six, the prototype chain:
1, definition: As the name implies, the prototype chain is a prototype chained together to form a prototype inheritance chain.
2, the structure of the prototype chain:
In the following code example, child inherits parent, parent inherits grandparent, and grandparent does not have a custom prototype, so the default is the topmost new Object () of the prototype chain;
(Why object is the topmost, because object.prototype is null, NULL is not a prototype)
prototype chain: Child, New Parent (), new grandparent (), new Object (); function grandparent () { this.name = ' grandparent '; THIS.A = 3; } Parent.prototype = new grandparent (); function Parent () { this.name = ' parent '; this.b = 2; } Child.prototype = new Parent (); function Child () { this.name = ' child '; THIS.C = 1; } var child = new Child (); Console.log (child); Child {name: ' Child ', c:1} Console.log (CHILD.A);//3 Console.log (child.b);//2 Console.log (child.c ); 1
3, the prototype chain additions and deletions to check:
Using the prototype chain description above, child---new Parent (), new grandparent (), new Object (), the instance object is child
(1), Increase:
Adding a property to a child instance object is always added as its own property, which has no effect on the prototype and the prototype chain. (In other words, the instance object constructed with the same constructor cannot be affected, as in the following statement)
(2), delete:
Use the delete operator to delete only the properties of the child instance object itself, but not the properties inherited by the prototype
(3), change:
In two cases:
If the modified property is inherited from the prototype, and the value type is the original value, only the property of the instance object is modified and cannot be affected by the prototype.
If the modified property is inherited from the prototype, and the property value type is a reference value, then the modification of the reference value is divided into two cases:
The first is to assign values directly to the modified property, and this condition only modifies the property of the instance object, which cannot affect the prototype.
The second is to add content to or remove content from the modified property, instead of re-assigning it-this condition affects the prototype. Here's an example:
Person.prototype = {have : [1, 2, 3] } function Person () { this.name = ' lyl '; } var person1 = new Person (); var person2 = new Person (); Person1.has.push (4); Both Person1 and Person2 have changed, as the Person1 modification affected the prototype, which in turn affected another instance object Console.log (Person1.has);//[1, 2, 3, 4] Console.log (Person2.has); [1, 2, 3, 4]
(4), check:
The query process is as follows, first see whether the constructor has to query the property, if any, then directly return, if not, then see if its prototype has to query the properties, if not, then see the prototype of the prototype has to query the properties, in this order in the prototype chain query, if the prototype chain until the top of the list still no properties to query Then return to undefined
P.s. Understand in the prototype chain of additions and deletions to change, nature can understand in the prototype of the additions and deletions, as long as the prototype on the additions and deletions as a prototype only a short prototype chain can be.
4, most of the objects will eventually inherit from Object.prototype
Why is it the overwhelming majority? Because null, and undefined are not prototypes, the above mentioned in detail
Vii. The history of object succession
Since this has been summed up before, so there is a direct link here: http://www.cnblogs.com/Walker-lyl/p/5592048.html
Viii. namespaces:
We can use objects to create namespaces to manage variables, to prevent contamination globally, for module development, such as the following simple demo:
var workSpace = { Person1: { name: ' One ', age:18 }, Person2: { name: ' Both ', age:20 }< c8/>}// so two people with the same name variable, but do not affect each other, because in different namespaces // access to the first person's name Console.log (workSpace.person1.name); One console.log (workSpace.person2.name);//two
Nine, implement a chain call similar to jquery: return this;
such as the next small demo, which this does not understand the matter, the above will say, you just put the second demo in the person object on the line
var person = { foodcount:10, eat:function () { this.foodcount--; return this; }, buy:function () { this.foodcount++; return this; }, print:function () { console.log (this.foodcount); } } Foodcount Initial value is 10, after eating three times, becomes 7 person.eat (). Eat (). Eat (); Person.print (); 7
X. Enumeration of objects:
1.obj.hasownproperty (' prop ');
The function of this method is to determine if the object obj has attribute prop in its own property,
The property itself is generated in the constructor, or the instance object is later added itself, and the inherited property is a property inherited from the prototype.
So the method is to determine whether the attribute is inherited from the prototype or its own.
Function: Iterates through all of the properties of an object, since the object traversal in ES5 is the default print that includes attributes inherited from the prototype, as shown in the demo
Person.prototype.age =; function person () { this.name = ' lyl '; } var person = new person (); unused hasOwnProperty //print: // lyl for (var prop in person) { console.log (Person[prop]); } // use hasOwnProperty //print: //Lyl for (var prop in person) { if ( Person.hasownproperty (prop)) { console.log (Person[prop]); } }
2, prop in obj;
The in operator is used to determine whether the property Prop,prop on the object obj can be either its own property or an inherited property, as shown in the following demo
Person.prototype.age =; function person () { this.name = ' lyl '; } var person = new person (); Console.log (' age ' in person); True console.log (' name ' in person);//true delete person.name; Console.log (' name ' in person); False
3, Object instanceof object;
The instanceof operator is used to determine whether an object instance is created by the objects constructor, as shown in the following demo
Person.prototype.age =; function person () { this.name = ' lyl '; } var person = new person (); Console.log (person instanceof person); True Console.log (New Object () instanceof person);//false
Xi. This basic introduction:
1. Function pre-compilation Process this-> window
2. this-> window in global scope
3, Obj.func (); The This in Func () points to obj, which can be understood so that who invokes Func, then this is the point to whom
4, call/apply can change the function run when this point,
(1), Call usage:
Func.call (to be changed after this, arg1, arg2, ...);
(2), Apply usage:
Func.apply (to be changed after this, [Arg1, Arg2, arg2]);
(3), apply and call in common: all change this point
Apply and call different points: The format of the parameter, call is to pass the parameters into one, and apply is to put all the parameters in an array, and then pass the array
The following demo:
Demo1 function Demo1 () { console.log (this); } Demo1 () <==> this.demo1 (); <==> window.demo1 () demo1 ();//window//Demo2 var demo2 = { retthis:function () { Console.log ( this); } } Demo2.retthis (); Demo2 = {...} Call/apply Change this demo1.call (DEMO2); Demo2 = {} demo2.retThis.call (window);//Window
12. Cloning of objects:
You might recall that you immediately complete the clone with an equal sign? It's also said, but you ignore the object is a reference value, the assignment operation assigns a reference to the object, and then it has a bad effect.
For example, assign Obj1 to Obj2, and then we add a property to Obj2, and then we will be pleasantly surprised to find that there is also a property in Obj1 that has just been added to the obj2, but I obj1 do not need this property ah, it caused obj1 unhappy, in order to make obj1 happy up, We looked down, hehe:
Object cloning, divided into shallow clones and deep clones, and the top of the direct assignment of the cloning operation for shallow cloning, why is called shallow cloning it? Because the cloned and cloned objects point to the same address reference when the cloning operation is complete, change one of them (note: The change here is to add or delete an object's properties instead of the object being re-assigned), and the other will change, while a deep clone will not produce this behavior.
Deep clone/Deep copy code as follows, this is the most complete and short code I have ever seen from the Internet, directly affixed to:
Deep cloning of objects (Array/obj/... ) function deepclone (obj) { var str, retobj = Object.prototype.toString.call (obj) = = = ' [Object Array] '? [] : {}; if (typeof obj!== ' object ') { return; } else if (window. JSON) { str = json.stringify (obj); Retobj = Json.parse (str); } else {for (var prop in obj) { Retobj[prop] = typeof Obj[prop] = = = ' object '? Deepclone (Obj[prop]): obj[prop];
} } return retobj; }
------------------------------------------end Here basically contains the I basic knowledge point of the object
JS Object (Classic)