1. The factory pattern abstracts the process of creating specific objects, but classes cannot be created in ECMAScript, so a function is used to encapsulate the details of creating objects with a specific interface. Take the following situation as an example,
has an employee class with name, age, and position attributes,
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 above method to define two employees, Jim, Sun
var Jim = CreateEmployee("jim", 22, "SoftWare Engineer");
var Sun = CreateEmployee("Sun",24,"Doctor");
Then use the SayName method respectively, Let two employees sign up
Jim.sayName( );
Sun.sayName();
The function CreateEmployee can construct an Employee object containing necessary information based on the parameters, and this function can be called unlimited times. Although the factory pattern solves the problem of creating multiple similar objects, it does not solve the problem of how to know the type of an object.