JavaScript design pattern Theory and example in-depth analysis (bottom)

Source: Internet
Author: User

6.2.4 combination using constructor mode and prototype mode (resolving instances of reference type values in prototype mode cannot be privatized)

The most common way to create a custom type is to combine the constructor pattern with the prototype pattern. The constructor pattern is used to define instance properties, and the prototype schema is used to define methods and shared properties. As a result, each instance will have its own copy of the instance properties, but at the same time it shares a reference to the method, saving the memory to a minimum . In addition, this blending pattern also supports passing parameters to the constructor, which is the length of the two modes. The following code overrides 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 ("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

In this example, the instance properties are defined in the constructor, and the properties constructor and Method Sayname () shared by all instances are defined in the prototype. modifying Person1.friends (Adding a new string to it) does not affect person2.friends, because they refer to different arrays respectively. This pattern of constructors and prototypes is the most widely used and most recognized method of creating custom types in ECMAScript. It can be said that this is a default pattern for defining reference types.


6.2.5 Dynamic Prototyping 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 by encapsulating all the information in the constructor, and by initializing the prototype in the constructor (only if necessary), while preserving the advantages of using both constructors and prototypes. In other words, you can determine whether a prototype needs to be initialized by checking that a method that should exist is valid. Take a look at an example.


function person (name, age, Job) {
Property
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 ();

Note The bold part of the constructor code. This is only added to the prototype if the Sayname () method does not exist. This code will only be executed when the constructor is first called. Since then, the prototype has been initialized and there is no need to make any changes. Keep in mind, however, that the modifications made to the prototype here can be immediately reflected in all instances . So this approach is really perfect. Where the If statement checks for any properties or methods that should exist after initialization--you do not have to examine each property and each method with a large heap of if statements, just check one of them. For objects created with this pattern, you can also use the instanceof operator to determine its type. You cannot use object literals to rewrite prototypes when using dynamic prototype mode. As explained earlier, if you rewrite the prototype with the instance already created, the connection between the existing instance and the new prototype will be severed.


6.2.6 Parasitic structural function pattern
In general, the parasitic (parasitic) constructor pattern can be used in situations where none of the aforementioned modes are applicable. The basic idea of this pattern is to create a function that encapsulates the code that creates the object, and then returns the newly created object, but on the surface, the function 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 appropriate properties and methods, and then returns the object. In addition to using the new operator and using the wrapper function called the constructor, this pattern is exactly the same as the factory pattern. The constructor returns a new object instance by default, without returning a value. Instead, you can override the value that is returned when the constructor is called by adding a return statement at the end of the constructor function. This pattern can be used in special cases to create constructors for objects . Suppose we want to create a special array with extra methods. This pattern can be used because the Array constructor cannot be modified directly.


Function Specialarray () {
//create array
var values = new Array ();
Add Value
values.push.apply (values, arguments);  //call takes a parameter table to accept the parameters of the called function
//Add method
Values.topipedstring = function () {
return This.join ("|");
};
//return array
return values;
}
var colors = new Specialarray ("Red", "Blue", "green");
Alert (colors.topipedstring ());//"Red|blue|green"
 
In this example, we created a constructor called Specialarray. Inside this function, an array is created first, and then the Push () method (all parameters received by the constructor) initializes the value of the array. A topipedstring () method is then added to the array instance, which returns the array values separated by a vertical bar. Finally, the array is returned in the form of a function value. We then called the Specialarray constructor, passed in the value used to initialize the array, and then called the Topipedstring () method. As for the parasitic constructor pattern, there is one thing to note: First, there is no relationship between the returned object and the constructor or the prototype of the constructor (
), that is, the object returned by the constructor is not the same as the object created outside the constructor. To do this, you cannot rely on the instanceof operator to determine the object type. Because of these problems, we recommend that you do not use this mode if you can use other modes.

6.2.7 Secure Structural function mode
Douglas Kest Rockford (Douglas Crockford) invented the concept of a secure object (durable objects) in JavaScript. The so-called secure object refers to the absence of a public property, and its method does not refer to the object of this . Secure objects are best suited for use in some secure environments where this and new are prohibited, or when data is being altered by other applications, such as mashup programs. The secure constructor follows a pattern similar to the parasitic constructor, but has a difference of two points: one is that the instance method of the newly created object does not refer to this, and the second is not to call the constructor with the new operator . According to the requirements of the safe constructor, the preceding
The person constructor is rewritten as follows.


function person (name, age, Job) {
To create an 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 that in objects created in this mode, there is no other way to access the value of name in addition to using the Sayname () method. You can use the secure person constructor as below.
var friend = person ("Nicholas", "Software Engineer");
Friend.sayname (); "Nicholas"
In this way, the variable friend holds a secure object, and 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, there is no way to access the raw data passed into the constructor. This security provided by the secure constructor pattern makes it ideal for environments in some secure execution environments-for example, Adsafe (www.adsafe.org) and Caja (http://code.google.com/p/google-caja/)- -Under use.


JavaScript design pattern Theory and example in-depth analysis (bottom)

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.