JavaScript Object-oriented object-creation notes

Source: Internet
Author: User
Tags constructor instance method safe mode uppercase letter advantage

1 Factory mode:
The factory model is a well-known design pattern in software engineering, which abstracts the process of creating concrete objects. Because ECMAScript cannot create a class, developers invent a function that encapsulates the details of creating an object with a specific interface. As follows:

The code is as follows Copy Code

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 ("Gothic", "21″," f2e ");
var person2 =createperson ("Greg", "27″, Doctor");

Here the function Creatperson () can build a person object containing all the necessary information according to the accepted parameters, and can call the function countless times, and each time it returns an object that contains a method of three attributes. The factory pattern solves the problem of creating multiple acquaintances, but does not solve the problem of object recognition (that is, how to get to know the type of an object), so it has the following pattern.
2. Constructor pattern
Functions in ECMAScript can be used to create objects of a particular type. Native constructors, such as object and array, automatically appear in the execution environment at run time. Of course, we can also create custom constructors that define the properties and methods of the custom object type. As follows:

The code is as follows Copy Code

function Person (name,age,job) {
THIS.name = name;
This.age = age;
This.job = job;
This.sayname = function () {
Alert (this.name)
};
}
var person1 = new Person ("Gothic", "f2e");
var person2 = new Person ("Greg", "Doctor");

The above example is rewritten using the constructor pattern. Now let's look at the difference between the two words:
The code in person () is in addition to the same part of Createperson (), with the following differences
1 The Creation object is not displayed;
2 directly assigns the attribute and method to this object;
3 There is no return statement.
PS: By convention, constructors should always start with an uppercase letter, whereas a constructor should start with a lowercase letter. However, the constructor itself is also a function, but it can be used to create objects.
Constructor: Constructor properties. The constructor of an object is initially used to identify the object type. However, to detect the object type, or to use the instanceof operation is a little more reliable, as follows:

The code is as follows Copy Code
Alert (Person1 instanceof Object); True
Alert (Person2 instanceof Object); 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.

The only difference between constructors and other functions is that they are invoked in a different way. Any function, as long as it is invoked through the new operator, can act as a constructor, and any function that is not invoked by the new operator will be no different from a normal function. For example, use the preceding example:

The code is as follows Copy Code

Use as a constructor function
var person = new Person ("Gothic", "f2e");
Person.sayname ()//"Gothic"

Call www.111cn.net as a normal function
Person ("Greg", "Doctor");
Windows.sayname ()//"Greg"

Called in the scope of another object
var o = new Object ();
Person.call (O, "K0risten", "Nurse");
O.sayname ()//"Kristen"

Constructor patterns are useful, but they are not without drawbacks. The main problem is that each method is recreated on each instance. That's the way it is. Creating a function results in different scope and identifier resolution, but the mechanism for creating new instances of a function is the same. So the functions of the same name on different instances do not want to wait, and can be judged by the following:
Alert (Person1.sayname = = Person2.sayname); False

3. Prototype mode
Each function we create has a prototype (prototype) attribute, which is a pointer to an object that is intended to contain properties and methods that can be shared by all instances of a particular type. The advantage of using a prototype object is that all object instances can share the properties and methods it contains. To be clear, it is not necessary to define the object instance's information in the constructor, but to add the information directly to the prototype object, as follows:

The code is as follows Copy Code

function person () {
}
Person.prototype.name = "Gothic";
Person.prototype.age = 21;
Person.prototype.job = "f2e";
Person.prototype.sayName = function () {
alert (this.name);

}
var person1 = new Person ();
Person1.sayname (); "Gothic"
var person2 = new Person ();
Person2.sayname (); "Gothic"
Alert (Person1.sayname = = Person2.sayname); True

To understand the working principle of the prototype model, we must first understand the nature of the ECMAScript central object.
The prototype pattern also has drawbacks, omitting the process of passing initialization parameters for constructors, resulting in the same property values being obtained by default for all instances. The biggest problem with prototyping patterns is that they are shared by nature.
Because all the properties in the prototype are shared by many instances, this share is appropriate for the function, but the problem is more pronounced for attributes that contain reference type values, as follows:

  code is as follows copy code

function () {

}
Person.prototype ={
Constructor:person,
Name: "Gothic",
Age:21,
Job: "f2e"
friends:[ Shelby "," Court "],
Sayname:function () {
alert (this.name);
}
} www.111cn.net
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

The above code lets you see that the Person.prototype object has a Friends attribute, which contains a string group, and then creates two instances of person and adds a string to the array of person1.friends references. Because the friends array exists in the person.prototype instead of the Person1, the addition of the modified is also reflected through the person2.friends. But sometimes we don't want it to be reflected in the person2.prototype, and the examples generally have their own attributes.

4. Combined use of constructor patterns and prototype patterns
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. The advantage is that each instance has its own copy of an instance attribute, but at the same time it shares each other's references, saving maximum memory, and this blending mode also supports passing parameters to the constructor;

  code is as follows copy code

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 ("Gothic", "f2e"),
var person2 =new person ("Greg", "Doctor");
Person1.friends.push ("Van");
Alert (person1.friends);//"Shelby,count,van"
Alert (person2.friends);//"Shelby,court"
Alert ( Person1.friends = = = Person2.friends); False
Alert (person2.friends = = person2.friends);//true

The model of this kind of constructor and prototype is the most widely used and highly identified method.

5 Dynamic Prototyping Mode
Dynamic Prototyping mode It encapsulates all the information in the constructor, and by initializing the prototype in the constructor, it retains the advantage of using both constructors and prototypes. As follows:

The code is as follows Copy Code

function Person (name,age,job) {
THIS.name = name;
This.age = age;
This.job = job;
if (typeof this.sayname!= "function") {
Person.prototype.sayName = function () {
alert (this.name);
};
}
}
var friend = new Person ("Gothic", "f2e");
Friends.sayname ();

The IF statement in the above code will only be added to the prototype if the Sayname () method does not exist. This code is only executed when the constructor is first invoked. Since then, the prototype has been initialized and no further modifications are made.
6. Parasitic structural function pattern
If the above modes are not applicable, we can try the parasitic constructor mode
The basic idea of this pattern is to create a function that simply encapsulates the code that creates the object and then returns the newly created object. As follows:

The code is as follows Copy Code

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 friends = new Person ("Gothic", "f2e");
Friends.sayname ()///"Gothic"

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. Dog-making function returns the new object instance by default, without returning a value. By adding a return statement at the end of the constructor, you can override the value returned when the constructor is called.
This pattern can be used to create constructors for objects at special times

On the parasitic constructor pattern we should note that the returned object fish constructor is not related to the stereotype property of the constructor, that is, the object returned by the constructor is not different from the object created outside the constructor. That is, you cannot rely on the instanceof operator to determine the object type, so I recommend that you do not use this pattern.
7. Safe constructor Mode
Our Douglas classmate invented the concept of "safe object" in JS. The so-called Safe object refers to objects that do not have public properties and whose methods do not refer to this object, which is suitable for use in some secure environments. The Safe Mode function pattern follows a pattern similar to a parasitic constructor (that is, the instanceof operator does not work with this object), but there are two differences: one is that the instance method of the newly created object does not reference this, and the second is to call the constructor without using the new operator. As required by the sound mode, we can rewrite:

The code is as follows Copy Code

function Person (name,age,job) {
var o =new Object ();
O.sayname = function () {
alert (name);
};
return o;
}

In addition to using the Sayname () method, the object created by this pattern has no other way to access the value of name. We may want to use the secure person constructor below.

The code is as follows Copy Code
var friend = person ("gothic", "f2e");
Friends.sayname (); Gothic

This friends saves a secure object, and there is no way to access the data members of the device other than to invoke the Sayname () method. Therefore, the safe mode is suitable to be used in some security execution environment.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.