"JavaScript" Factory method

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.