1. Factory mode
Factory mode abstracts the process of creating concrete objects, using functions to encapsulate the details of creating objects with specific interfaces.
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 personone = Createperson ("Ali", "bussiness");
var = createperson ("Baidu", Persontwo, "software engineer");
2. Constructor mode
Constructors in ECMAScript can be used to create specific types of objects, such as object and array native constructors, which automatically appear in the execution environment at run time. In addition, you can customize the constructors to customize the properties and methods of the object type.
function Person (name,age,job) {
THIS.name = name;
This.age = age;
This.job = job;
This.sayname = function () {
alert (this.name);
};
}
var personone = new Person ("Ali", "bussiness");
var persontwo = new Person ("Baidu", "software Engineer");
Creating a custom constructor means that its instance can be identified as a specific type in the future, where the constructor pattern is better than the factory pattern.
2.1 Use constructors as functions
Any function that is called with the new operator can be used as a constructor, and not by the new operator, which is no different from a normal function.
Called as a constructor function
var person = new Person ("Ali", +, "bussiness");
Person.sayname (); "Ali"
Called as a normal function
Person ("Tengxun", "bussiness"); Add to Window
Window.sayname (); "Tengxun"
Called in the scope of another object
var o = new Object ();
Person.call (O, "Baidu", "anger");
O.sayname (); "Baidu"
2.2 Constructor problems
function Person (name,age,job) {
THIS.name = name;
This.age = age;
This.job = job;
This.sayname = Sayname;
}
function Sayname () {
alert (this.name);
}
var personone = new Person ("Ali", "bussiness");
var persontwo = new Person ("Baidu", "software Engineer");
The Personone and Persontwo objects share the same sayname () function defined at the global scope.
2.3 Prototype Mode
JavaScript Create objects