JavaScript Creation Object-Factory mode

Source: Internet
Author: User

1 functionCreateperson (name, age) {2     varo =NewObject ();3O.name =name;4O.age =Age ;5O.sleep =function() {6Alert ("Sleeping ...");7     }8     returno;9 }Ten varP1 = Createperson ("cai10", 22); One varP2 = Createperson ("Cai20", 25); A alert (p1.name); - alert (p1.age); - p1.sleep (); theAlerttypeofp1); -Alert (P1instanceofObject); - alert (p1.constructor); -Alert (P1.sleep = =p2.sleep); + //cai10 - // A + //Sleeping ... A //Object at //true - //function Object () { - //[native code] - // } - //false

Factory mode, that is, a function to encapsulate the details of creating an object with a specific interface.
The function Createperson () can create a person object that contains the necessary information by accepting parameters.
You can call this function multiple times, returning an object that contains two properties and a method at a time.
However, it is not possible to know the type of an object, that is, the object type cannot be determined by Typeof,constructor.
In addition, p1 and P2 have a sleep () method, but they are not the same function instance, it is not necessary to create two identical function instances,
The subsequent creation of object patterns will resolve these issues.

If there is any mistake, please correct me, thank you ...

JavaScript Creation Object-Factory mode

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.