constructor that is used to construct the object. Also called the factory Way "raw materials, processing, factory"
Empty object, equivalent to "raw material"
Add properties and methods to the object, equivalent to "machining"
Return the object, equivalent to "factory"
Factory mode "raw material, processing, factory" function Createperson (name,gender) {//constructor, used to construct the object var obj=new object ();//Empty object, equivalent to "raw material" // Adding properties and methods to the object is equivalent to "processing" the obj.name=name; Obj.gender=gender; Obj.showname= function () { alert ("I Call:" +obj.name) }; obj.showgender= function () { alert ("I Am" +obj.gender+ ") }; Return obj;//the object, equivalent to "factory"}var Person1=createperson ("Syr", "female"), Var Person2=createperson ("Xixi", "male"); Person1.showname ();p erson1.showgender ();p erson2.showname ();p erson2.showgender ();
This looks pretty clear, but at this point the factory method has two drawbacks
First, there is no new (workaround: Precede the function with new)
Second, each object has its own function, which wastes resources?
Here's another way to do this without "solving the first problem" with the new object and the return object.
1 functionCreateperson (Name,gender) {//constructors, for constructing objects2 //var this=new Object (); The system defaults to a new3 This. name=name;//Change to this4 This. gender=gender;5 This. showname=function () {6Alert ("I call:" + This. Name)7 };8 This. showgender=function () {9Alert ("I am" + This. gender+ "of")Ten }; One //return this; system default return A } - varperson1=NewCreateperson ("Syr", "female"); - varPerson2=NewCreateperson ("Xixi", "male"); the person1.showname (); - Person1.showgender (); - person2.showname (); -Person2.showgender ();
to solve the second problem, take a look at the next "prototype"
"JavaScript" Factory method