JavaScript creates objects in the following ways:
1. Use the object constructor to create an object
The following code creates a person object and prints the property value of name in two ways.
var person = new Object ();
Person.name= "Kevin";
person.age=31;
alert (person.name);
Alert (person["name"])
Another manifestation of the above notation is the use of object literals to create an object, not strange person["5"], where it is legal, and the way in which parentheses can have spaces between fields such as person["my age".
var person =
{
name: "Kevin",
age:31,
5: "Test"
};
alert (person.name);
Alert (person["5"]);
Although the object constructor or object literal can be used to create a single object, there is an obvious drawback: using the same interface to create many objects produces a lot of duplicate code. To solve this problem, people began to use a variant of the factory pattern.
2. Factory mode
The factory model is a well-known design pattern in the field of software engineering, which abstracts the process of creating objects and, given the inability to create classes in ECMAScript, developers invent a function that encapsulates the details of creating objects with a specific interface, as shown 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");
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 JavaScript
Development, another new model has emerged.
3. Constructor pattern
constructors, such as object and array, automatically appear in the execution environment at run time. In addition, you can create custom constructors that define properties and methods for custom object types. For example, you can use the constructor pattern to rewrite the preceding examples as follows.
function person (name, age, Job) {
this.name = name;
This.age = age;
This.job = job;
This.sayname = function () {
alert (this.name);}
;
} var person1 = new Person ("Nicholas", "Software Engineer");
var person2 = new Person ("Greg", "Doctor");
In this example, the person () function replaces the Createperson () function. We notice that the code in person () has the following differences in addition to the same part as in Createperson ():
1, did not explicitly create the object;
2, directly to the properties and methods assigned to this object;
3, no return statement.
To create a new instance of person, you must use the new operator. Calling a constructor in this way actually goes through the following 4 steps:
(1) Create a new object;
(2) Assign the scope of the constructor to the new object (so this points to the new object);
(3) Executing the code in the constructor (adding attributes for this new object);
(4) Returns the new object.
At the end of the previous example, Person1 and Person2 each hold a different instance of person. Both objects have a constructor (constructor) property that points to the person, as shown below.
Alert (Person1.constructor = = person); True
Alert (Person2.constructor = = person); True
The constructor property of an object is initially used to identify the object type. However, it is more reliable to refer to the detection object type or the instanceof operator. All the objects we create in this example are both instances of object and instances of person, which can be validated by the instanceof operator.
Alert (Person1 instanceof Object); True
Alert (person1 instanceof person); True
Alert (Person2 instanceof Object); True
Alert (person2 instanceof person); True
Creating a custom constructor means that its instance can be identified as a specific type in the future, which is where the constructor pattern trumps the factory pattern. In this example, Person1 and Person2 are both instances of object because all objects inherit from object.
Problems with constructors
Constructor patterns are useful, but they are not without drawbacks. The main problem with constructors is that each method is recreated on each instance.
The functions in ECMAScript are objects, so each definition of a function is an instantiation of an object. In a logical sense, the constructor at this point can also be defined as this.
function person (name, age, Job) {
THIS.name = name;
This.age = age;
This.job = job;
This.sayname = new Function ("Alert (this.name)"); is logically equivalent to declaring a function.
}
From this perspective, the constructor is easier to understand the nature of each person instance that contains a different function instance to display the Name property. To be clear, creating a function in this way results in different scope chains and identifier resolutions, but the mechanism for creating new instances of a function remains the same. Therefore, the functions of the same name on different instances are not equal, as the following code can prove.
Alert (Person1.sayname = = Person2.sayname); False
However, it is really not necessary to create two function instances to accomplish the same task, and the This object is not bound to a specific object before executing the code. Therefore, you can solve this problem by moving the function definition outside of the constructor as follows.
function person (name, age, Job) {
this.name = name;
This.age = age;
This.job = job;
This.sayname = Sayname;
}
function Sayname () {
alert (this.name);
}
var person1 = new Person ("Nicholas", "Software Engineer");
var person2 = new Person ("Greg", "Doctor");
If an object needs to define many methods, there are many global functions to be defined, so our custom reference type has no encapsulation whatsoever. Fortunately, these problems can be solved by using prototyping patterns.
4. Prototype mode
function person () {
}
Person.prototype.name = "Nicholas";
Person.prototype.age =;
Person.prototype.job = "Software Engineer";
Person.prototype.sayName = function () {
alert (this.name);
};
var person1 = new Person ();
Person1.sayname (); "Nicholas"
var person2 = new Person ();
Person2.sayname (); "Nicholas"
alert (person1.sayname = = person2.sayname);//true
To understand the prototype object, I can see another article: JavaScript prototype detailed
In the previous example, each addition of a property and method will be knocked Person.prototype. To reduce unnecessary input and to visually better encapsulate the functionality of the prototype, it is more common to rewrite the entire prototype object with an object literal that contains all the properties and methods, as shown in the following example.
function person () {
}
person.prototype = {
name: "Nicholas",
age:29,
job: "Software Engineer ",
sayname:function () {
alert (this.name);
}
};
In the code above, we set the person.prototype to be equal to a new object created in the literal form of an object. The end result is the same, with one exception: the constructor property no longer points to person. As described earlier, each time you create a function, it creates its prototype object, and the object automatically gets the constructor attribute. The syntax we use here essentially overrides the default prototype object, so the constructor property becomes the constructor property of the new object (pointing to the object constructor) and no longer points to the person function. At this point, although the instanceof operator can return the correct result, the object's type cannot be determined by constructor, as shown below.
var friend = new person ();
Alert (friend instanceof Object); True
alert (friend instanceof person);//true
alert (friend.constructor = = person);//false
alert ( Friend.constructor = = Object); True
Here, test object and person with the instanceof operator still returns true, but the constructor property equals object instead of person. If the value of constructor is really important, you can deliberately set it back to the appropriate value as follows.
function person () {
}
person.prototype = {
Constructor:person,
name: "Nicholas",
age:29,
Job: "Software Engineer",
sayname:function () {
alert (this.name);
}
;
One thing to be aware of is that pointers in an instance point to only the prototype, not to the constructor.
Problem with the prototype object: The prototype model is not without drawbacks. First, it omits the process of passing initialization parameters for constructors, resulting in the same property values being obtained by default for all instances. While this may be inconvenient in some way, it is not the biggest problem with prototypes. The biggest problem with archetypal patterns is that they are shared by nature.
function person () {
}
person.prototype = {
Constructor:person,
name: "Nicholas",
age:29,
Job: "Software Engineer",
friends: ["Shelby", "Court"],
sayname:function () {
alert (this.name);
}
};
var person1 = new Person ();
var person2 = new Person ();
Person1.friends.push ("Van");
alert (person1.friends); "Shelby,court,van"
alert (person2.friends);//"Shelby,court,van"
alert (person1.friends = = Person2.friends); True
5. Combining constructor mode and prototype mode (most commonly used)
The most common way to create custom types is to combine the constructor pattern with the prototype pattern. The constructor pattern is used to define instance properties, which are used to define methods and shared properties. As a result, each instance has its own copy of an instance attribute, but at the same time it shares a reference to the method, saving maximum memory. In addition, this hybrid model also supports the transfer of parameters to the constructor, which is the length of the set of two modes.
function person (name, age, Job) {
this.name = name;
This.age = age;
This.job = job;
This.friends = ["Shelby", "Court"];
}
Person.prototype = {
Constructor:person,
sayname:function () {
alert (this.name);
}
}
var person1 = new Person ("Nicholas", "Software Engineer");
var person2 = new Person ("Greg", "Doctor");
Person1.friends.push ("Van");
alert (person1.friends); "Shelby,count,van"
alert (person2.friends);//"Shelby,count"
alert (person1.friends = = = Person2.friends ); False
alert (person1.sayname = = person2.sayname);//true
6. Dynamic prototype mode
Developers with other OO language experiences are likely to be very confused when they see independent constructors and prototypes. The dynamic prototyping model is a solution to this problem, encapsulating all the information in the constructor, and maintaining the advantage of using constructors and prototypes in the constructor by initializing the prototype (only where necessary). In other words, you can determine whether you need to initialize a prototype by checking whether a method that should exist is valid. Take a look at an example.
function person (name, age, Job) {
//attribute
this.name = name;
This.age = age;
This.job = job;
Method
---------------------------------------------
if (typeof this.sayname!= "function") {
Person.prototype.sayName = function () {
alert (this.name);}
;
} --------------------------------------------
}
var friend = new Person ("Nicholas", "Software Engineer") ;
Friend.sayname ();
7. Parasitic structural function pattern
In general, a parasitic (parasitic) constructor pattern can be used in cases where none of the preceding modes are applicable. The basic idea of this pattern is to create a function that encapsulates only the code that creates the object, and then returns the newly created object, but on the surface it looks like a typical constructor. Here is an example.
function person (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 friend = new Person ("Nicholas", "Software Engineer");
Friend.sayname (); "Nicholas"
In this example, the person function creates a new object, initializes the object with the corresponding property and method, and then returns the object. In addition to using the new operator and using a wrapper function called a constructor, this pattern is exactly the same as the factory pattern. When a constructor does not return a value, the new object instance is returned by default.
8, the Safe construction function pattern
A trustworthy object is one that does not have a public property and its methods do not refer to this object. Secure objects are best used in some secure environments where this and new are prohibited, or when data is prevented from being altered by other applications, such as mashup programs. A secure constructor follows a pattern similar to a parasitic constructor, but has two different points: one is that the instance method of the newly created object does not reference this, and the constructor is not invoked with the new operator. The preceding person constructor can be rewritten as follows, as required by a secure constructor.
function person (name, age, Job) {
//Create object to return
var o = new Object ();
Here you can define private variables and functions
//Add methods
O.sayname = function () {
alert (name);
Returns the object return
o;
}