In-depth analysis of javascript design patterns theories and examples (II) and javascript Design Patterns

Source: Internet
Author: User

In-depth analysis of javascript design patterns theories and examples (II) and javascript Design Patterns
6.2.4 use the constructor mode and prototype mode in combination (to solve the issue that instances that cannot reference type values in prototype mode cannot be privatized)

The most common way to create a custom type is to combine the constructor mode and the prototype mode. The constructor mode is used to define instance attributes, while the prototype mode is used to define methods and shared attributes. Result,Each instance has its own copy of the Instance attribute, but it also shares the reference to the method, saving the memory to the maximum extent.. In addition, this mixed mode also supports passing parameters to the constructor. The following code overwrites the previous example.


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 ("Nicolas", 29, "Software Engineer ");
Var person2 = new Person ("Greg", 27, "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
 

In this example, the instance attributes are defined in the constructor and the method sayName () shared by all instances are defined in the prototype. The modification of person1.friends (adding a new string to it) does not affect person2.friends, because they reference different arrays. This constructor and prototype are the most widely used methods in ECMAScript to create custom types. It can be said that this is a default mode used to define the reference type.


6.2.5 Dynamic Prototype

Developers with experience in other OO languages may be very confused when they see independent constructors and prototypes. The dynamic prototype is a solution dedicated to solving this problem. It encapsulates all information in constructors, by initializing the prototype in the constructor (only when necessary), the advantage of using the constructor and prototype at the same time is maintained. In other words, you can determine whether to initialize the prototype by checking whether a method that should exist is valid. Let's look at an example.


Function Person (name, age, job ){
// Attributes
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 ("Nicolas", 29, "Software Engineer ");
Friend. sayName ();
 
Note the bold part in the constructor code. The method is added to the prototype only when the sayName () method does not exist. This code is executed only when the constructor is called for the first time. After that, the prototype has been initialized and does not need to be modified. But remember,Modifications made to the prototype can be immediately reflected in all instances.. Therefore, this method is indeed perfect. Among them, the if statement can check any attribute or method that should exist after initialization -- you don't have to use a lot of if Statements to check each attribute and each method; you just need to check one of them. For an object created in this mode, you can also use the instanceof operator to determine its type. When using the dynamic prototype mode, you cannot use the object literal to override the prototype. As explained above, if the prototype is rewritten when an instance has been created, the connection between the existing instance and the new original type will be cut off.


6.2.6 parasitic constructor Mode
In general, the parasitic constructor mode can be used if none of the preceding modes are applicable. The basic idea of this mode is to create a function. The function is only used to encapsulate the code for creating an object and then return the newly created object. But on the surface, this function looks like a typical constructor. The following 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 ("Nicolas", 29, "Software Engineer ");
Friend. sayName (); // "Nicolas"
 
In this example, the Person function creates a new object, initializes the object with the corresponding attributes and methods, and then returns the object. In addition to using the new operator and calling the wrapped function constructor, this mode is exactly the same as the factory mode. If no value is returned, the constructor returns a new object instance by default. By adding a return statement at the end of the constructor, You can override the value returned when calling the constructor. This mode can be usedObject creation Constructor. Suppose we want to create a special array with additional methods. You can use this mode because you cannot directly modify the Array constructor.


Function SpecialArray (){
// Create an array
Var values = new Array ();
// Add Value
Values. push. apply (values, arguments); // call uses a parameter table to accept the parameters of the called function.
// Add Method
Values. toPipedString = function (){
Return this. join ("| ");
};
// Returns an array.
Return values;
}
Var colors = new SpecialArray ("red", "blue", "green ");
Alert (colors. toPipedString (); // "red | blue | green"
 
In this example, we create a constructor named SpecialArray. In this function, an array is created first, and the value of the array is initialized by the push () method (all parameters received by the constructor. Then, a toPipedString () method is added to the array instance. This method returns the array value separated by a vertical line. Finally, return the array as a function value. Then, we call the SpecialArray constructor, pass in the value used to initialize the array, and then call the toPipedString () method. One thing to note about the parasitic constructor mode is: first, the returned object and constructor, or the prototype of the constructor.
There is no relationship between them; that is, the objects returned by the constructor are no different from those created outside the constructor. Therefore, the instanceof operator cannot be used to determine the object type. Because of the above problems, we recommend that you do not use this mode when other modes are available.

6.2.7 secure constructor Mode
Douglas Crockford invented the durable objects concept in JavaScript. The so-calledA secure object refers to an object without a public attribute and its method does not reference this.. Secure objects are best suited to some secure environments (this and new are not allowed in these environments), or to prevent data from being changed by other applications (such as Mashup programs. The safe constructor follows a pattern similar to the parasitic constructor, but there are two differences:First, the instance method of the new object does not reference this; second, the new operator is not used to call the constructor.. According to the requirements of the secure constructor
The Person constructor is rewritten as follows.


Function Person (name, age, job ){
// Create the object to return
Var o = new Object ();

// Private variables and functions can be defined here
// Add Method
O. sayName = function (){
Alert (name );
};
// Return object
Return o;
}
Note: In the objects created in this mode, there is no way to access the value of name except the sayName () method. You can use a secure Person constructor as follows.
Var friend = Person ("Nicolas", 29, "Software Engineer ");
Friend. sayName (); // "Nicolas"
In this way, the variable "friend" stores a secure object. In addition to calling the sayName () method, there is no other way to access its data members. Even if other Code adds methods or data members to the object, it is impossible to access the original data passed into the constructor. The secure constructor model provides this security, making it ideal for use in some secure execution environments, such as those provided by ADsafe (www.adsafe.org) and Caja (http://code.google.com/p/google-caja.


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.