Objects have three main features: encapsulation, inheritance, polymorphism
First, the package
1. The encapsulation of functions is for the security of functions, wrapping objects, and derivation of different objects through finite interfaces
2. Factory function Encapsulation
The factory function is a kind of argument in the design model, not through the class instantiation constructor, but through the function constructs the object, creates an object inside the function, implements the object through the parameter pass through the control, and returns the object, when the property is simultaneously causes the memory waste.
//(An object is created in the function, and the object's property value is passed in by itself.) functionPerson (Name,age,say) {varobj ={}; Obj.name=name; Obj.age=Age ; Obj.say=say;//Callback returnobj; } functionSay1 () {alert (Speak) } functionSay2 () {alert (Laugh) } varls =person (' ls ', 16,say2);//(no constructor required, the return value received is itself an object) varZS =person (' Zhangsan ', 18, Say1); //(Zs becomes object, receives the return value of the factory function)
3. Constructor encapsulation
function Person (name,age) { this. name=name; this. age= age;} Person.prototype.say=function() { alert ("Speak")}var zs=New person ("Zs",N); var ls=New person ("ls",Zs.say (); Ls.say ();
Console.log (ls instanceof Object) //true
Console.log (ls instanceof person) //true
// The common code snippet is stored in the prototype prototype and its properties are fixed, immutable
4. The similarities and differences between constructors and factory functions
1) The factory function needs to create the object, and must have a return value
2) The factory function is targeted at object model, and the constructor can match the custom object model
3) Factory functions can only add new properties and methods locally, constructors can be overridden, new properties and methods are added to the global
4) The constructor defines the same local variable in the global, it is easy to cause the global pollution, the this.xx is not obtained in the local, it will get to the global.
Second, inheritance (Implementation of code re-use)
1. Principle of Inheritance: Copy
1) deep copy: Copy the value of the object
2) Shallow copy: Copy the address of the object, affecting the property value of the source object
varJson={name: "Zhangsan", Age:12,son:{name: "Lisi"}} varjson1=copy (JSON)//Shallow Copy functionCopy (JSON) {varnewobj={} for(varIinchJSON) {Newobj[i]=Json[i]}returnnewobj; } json1.son.name= "Lisi1"Console.log (json.son.name)//LISI1 //Deep Copy functionCopy (JSON) {varnewobj={}; for(varIinchJSON) { if(typeofjson[i]== "Object") {Newobj[i]=copy (Json[i])}Else{Newobj[i]=Json[i]}} returnnewobj} json1.son.name= "Lisi1"Console.log (json.son.name)//Lisi
2.
Properties of the javascript--object