| 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.