Javascript object-oriented design-factory Model

Source: Internet
Author: User

1. The factory mode abstracts the process of creating a specific object, but the class cannot be created in ECMAScript. Therefore, a function is used to encapsulate the details of creating an object with a specific interface. Take the following situation as an example,
There is an employee class with attributes such as name, age, and position,
Copy codeThe Code is as follows: function CreateEmployee (name, age, job ){
Var Emp = new Object ();
Emp. name = name;
Emp. age = age;
Emp. job = job;
Emp. sayName = function (){
Alert (this. name );
};
Return Emp;
}

Use the preceding method to define two employees, Jim and Sun.
Copy codeThe Code is as follows:
Var Jim = CreateEmployee ("jim", 22, "SoftWare Engineer ");
Var Sun = CreateEmployee ("Sun", 24, "Doctor ");

Then we use the SayName method to let the two employees report their names.
Copy codeThe Code is as follows:
Jim. sayName ();
Sun. sayName ();

The CreateEmployee function can be used to construct an Employee object containing necessary information based on parameters. This function can be called infinitely. Although the factory mode solves the problem of creating multiple similar objects, it does not solve the problem of how to know an object type.

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.