1 /**2 * Created by 2016/6/4.3 */4 functionBox () {5 varobj =Newobj ();6Obj.name = "Lee";7Obj.run =function(){8 return This. name+ "Run";9 };Ten returnobj; One } A varB =Box (); - //The Factory mode creation object creates obj in the object and returns the Obj object at the end - the - - functionBox () { - This. Name = "Lee"; + This. Run =function(){ - return This. name+ "Run"; + }; A } at varB =NewBox (); - //constructor mode using the new operator to create an object - - - - functionBox () {}; inBox.prototype.name = "Lee"; -Box.prototype.run =function(){ to return This. name+ "Run"; + }; - the varB =NewBox (); * //prototype mode creation, prototype as the prototype attribute. $ //Pros: Method sharing, Cons: attribute sharingPanax Notoginseng - the + functionBox () {}; ABox.prototype = { theConstructor:box,//force point to box prototype, otherwise point to object +Name: "Lee", -Runfunction(){ $ return This. name+ "Run"; $ } - }; - varB =NewBox (); the //prototype mode, created in literal form. The literal cannot be overridden here, causing the previous connection to break - //Cons: Cannot pass parameters, all properties are sharedWuyi the - Wu functionBox () { - This. Name = "Lee"; AboutBox.prototype.run =function(){ $ return This. name+ "Run"; - }; - }; - varB =NewBox (); A //prototype + constructor pattern creation, where the run of each instance is initialized once, so you can use dynamic prototypes + constructs + //function Mode the - functionBox () { $ This. Name = "Lee"; the if(typeofBox.prototype.run! = "function"){ theBox.prototype.run =function(){ the return This. name+ "Run"; the }; - } in the }; the varDNewBox (); About the //dynamically created. The run will only be initialized once, and the method is shared, saving memory the the //There are many ways to create objects, and it is better to create them using the dynamic prototype + constructor pattern. + //instance properties are independent and method-shared.
There are a few more to add tomorrow ~
Several ways to create JavaScript objects