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.