JavaScript Factory mode: function Createperson ()

Source: Internet
Author: User

Article Introduction: The factory model is a well-known design pattern in software engineering, which abstracts the process of creating concrete objects. Given the inability to create classes in ECMAScript, developers invented a function that encapsulates the details of creating objects with a specific interface.

The factory model is a well-known design pattern in software engineering, which abstracts the process of creating concrete objects. Given the inability to create classes in ECMAScript, developers invented a function that encapsulates the details of creating objects with a specific interface, as in the following example:

function Createperson (name, age, Job) {
    var o = new Object ();
    O.name = name;
    O.age = age;
    O.job = job;
    O.sayname = function () {
        alert (this.name);
    };
    return o;
}

var person1 = Createperson ("Nicholas", "Software Engineer");
var person2 = Createperson ("Greg", "Doctor");

Person1.sayname (); "Nicholas"
person2.sayname ()//"Greg"

The function Createperson () can build a person object that contains all the necessary information based on the accepted parameters. This function can be called countless times, and each time it returns an object that contains a method of three properties. Although the factory pattern solves the problem of creating multiple similar objects, it does not solve the problem of object recognition (that is, how to know the type of an object). With the development of JavaScript, another new pattern has emerged.



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.