Home >Web Front-end >JS Tutorial >Javascript object-oriented design 1 factory pattern_js object-oriented

Javascript object-oriented design 1 factory pattern_js object-oriented

WBOY
WBOYOriginal
2016-05-16 17:58:091247browse

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,

Copy code The 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 above method to define two employees, Jim, Sun
Copy the code The code is as follows:

var Jim = CreateEmployee("jim", 22, "SoftWare Engineer");
var Sun = CreateEmployee("Sun",24,"Doctor");

Then use the SayName method respectively, Let two employees sign up
Copy the code The code is as follows:

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.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn