Overview of the Monomer mode:
A monomer is a class that can only be instantiated once and accessed through a well-known access point.
A monomer is an object that is used to divide a namespace and organize a group of related methods and properties together. If it can be instantiated, he can only be instantiated once.
The separation of the monomer object;
1. Not all object literals are monomers. If he just used to imitate associative arrays or accommodate data, it would not be a monomer.
2. If you are using to organize a batch of related methods and attribute sessions. It could be a monomer.
1. Basic structure of monomer
The simplest monomer is actually an object literal, which organizes a group of methods and properties with certain associations
var Singleton = {
Attribute1:true,
Attribute2:10,
Method1:function () {
},
Method2:function () {
}
}
Class Analysis:
1. This monomer object is modified. You can add new members to an object.
2. You can use the delete operator to delete its existing members.
3. Principles of object-oriented design: Classes can be extended, but cannot be modified.
5.2 Dividing namespaces
A monomer object consists of two parts:
The object itself that contains the methods and property members. And the variables used to access it. (this variable is usually global so that it can be accessed directly from anywhere on the page to the individual object it points to.) This is one of the main points of the monomer model.
Namespaces are an important tool for reliable JavaScript programming.
To avoid inadvertently changing variables, one of the best workarounds is to use a single object to organize your code into namespaces.
var MyNamespace = {
Findproduct:function (ID) {
}
}
Analysis:
1. Now the Findproduct function is a MyNamespace method that is not overwritten by any new variables declared in the global namespace.
2. Use namespaces to organize similar methods together. helps enhance the documentation of your code.
Namespaces are further segmented.
A variety of JavaScript code can appear in the global namespace.
To avoid conflicts, you can define a global object that contains all of your own code:
var Giantcorp = {};
2. You can then organize your code and data into various objects in this global object in a stuffy class:
Giantcorp.common = {
}
5.3 Monomer used as a wrapper for a specific Web page special code
Scenario Description:
In a Web site with many Web pages, some JavaScript code is used for all pages, so they are stored in separate files, some of which are specific to a particular Web page. will not be used anywhere else.
Recommendation: Finally, the two types of code are wrapped in their own monomer object.
The skeleton of a monomer that wraps special code for a particular webpage:
Namespace.pagename = {
Constant_1:true,
Constant_2:10,
Method1:function () {
},
Method2:function () {
}
Init:function () {
}
}
5.4 Monomers with private members
5.4.1 Using underline notation
1. It is easiest to create a private member within a single object. The most straightforward approach is to use the underscore notation.
2. Using underscore notation in a single object is a concise way to warn other programmers not to access specific members directly
Giantcorp.dataparser = {
_stripwhitespace:function (str) {
Return Str.replace (/\s+/, ");
},
_stringsplit:function (Str,delimiter) {
Return Str.split (delimiter)
},
String:function (STR,DELIMITER,STRIPWS) {
if (STRIPWS);
str = this.__stripwhitespace (str);
var Outputarray = This._stringsplit (Str,delimiter);
return outputarray;
}
}
5.4.2 uses closures
The second method of creating a private member in a singleton object requires closure, which is very similar to the practice of creating a true Private member in Chapter 3rd. But there is one (important difference)
1. The previous practice is that variables and functions are defined in the constructor body, making him a private member. The
2. Constructor body defines all the privileged methods and uses the This keyword to make it accessible to the outside world.
3. Each time an instance of the class is generated, all methods and properties within the declared constructor are created again.
monomer mode using closures:
1. monomers are only instantiated once. Don't worry about how many members you declare in the constructor.
2. Each property and method will be created once. All can declare them inside the constructor
mynamespace.singleton = {};
Create a function that executes immediately after a definition creates a monomer:
mynamespace.singleton = function{
return{};
} ();
function and analysis of the class:
1. The second example does not copy a function to Mynamespace.singleton.
2. The anonymous function returns an object of the class, which is exactly the object assigned to the Mynamespace.singletion variable.
3. In order to understand the execution of this anonymous function, simply place a stack of parentheses behind the last curly brace of its definition.
5.4. Comparison of 32 different technologies
Look at the Dataparser example to see how the real private member is used in its implementation, not by underlining for each private method.
Giantcorp.dataparser = (function () {
Private properties
var while =/\s+/;
Private methods
function Stripwhitespace (str) {
Return str.replace (while, ');
}
function Stringsplit (str,delimiter) {
Return Str.split (delimiter);
}
return {
Stringtoarray:function (STR,DELIMITER,STRIPWS) {
if (STRIPWS) {
str = stripwhitespace (str);
}
}
var Outputarray = Stringsplit (Str,delimiter);
Retrun Outputarray;
}
})();
Class Analysis:
1. These private methods and properties can now be accessed directly by their names without having to precede them with "this." or "dataparser." These prefixes are used only to access the public members of the monomer object.
Some advantages of this pattern comparison with the use of underline notation
1. Placing a private member in a closure ensures that it is not used outside of the monomer object.
2. You can freely change the implementation details of the object. Doesn't hurt anyone else's code.
3. This method protects and encapsulates the data.
Benefits of the Monomer model:
1. When using this model, you can enjoy all the benefits of a true private member.
2. The monomer class will only be instantiated once.
3. Monomer mode is one of the most popular and widely-used patterns of JavaScript.
5.5 Lazy Instantiation:
There is one thing in common about the various ways in which the monomer pattern is described earlier:
1. Individual objects are created when the script is loaded
2. For resource-intensive or highly-configured monomers, create objects when needed. This technique is called lazy loading.
3. As a namespace. A code wrapper specific to a particular Web page, or an organization-related practical method, is loaded immediately.
4. The special place of lazy loading monomers. Access to them must be aided by a static.
Call mode: Singleton.geninstance (). MethodName () instead of calling: Singleton.methodname ().
The 5.getinstace method checks to see if the monomer has been instantiated. If not. Then it will create and return its instance. An instance that has already been instantiated will return the current instance.
6. Convert the normal monomer into an inert loading monomer:
Mynamespace.singleton = (function () {
var privateAttribute1 = false;
var = [PrivateAttribute2];
function PrivateMethod1 () {
}
function PrivateMethod2 (args) {
}
return {
Publicattribute1:true,
Publicattribute2:10,
Publicmethod1:function () {
},
Publicmethod2:function () {
}
}
})()
Conversion The first step: Move all the code of the monomer into a method named constructor:
Mynamespace.singleton = (function () {
function Constructor () {
var privateAttribute1 = false;
var = [PrivateAttribute2];
function PrivateMethod1 () {
}
function PrivateMethod2 (args) {
}
return {
Publicattribute1:true,
Publicattribute2:10,
Publicmethod1:function () {
},
Publicmethod2:function () {
}
}
}
})()
Class Analysis:
1. This method cannot be accessed from outside the closure, so we can take full control of the timing of the call.
2. Public method getinstances is used to control the realization of this control.
3.getInstace to become a public method, you need to put an object literal return object;
Examples
Mynamaespace.singleton = (function () {
function Constructor () {
}
return {
getinstace:{
}
}
})()
Writing code to control the timing of the instantiation of a monomer class requires two things:
1. It is important to know if the class has been instantiated.
2. If the class has already been instantiated. Then he needs to master his strength so that he can return to the case.
3. Doing these two things requires an existing private method with a private property constructor
Mynamespace.singleton = (function () {
var uniqueinstace;
function constructor () {}
return {
Getinstace:function () {
if (uniqueinstace) {
Uniqueinstace = Constructor ();
}
return uniqueinstace;
}
}
})()
Call mode: Mynamespace.singleton.getinstace (). PUBLICMETHOD1 ();
Namespace too long simplified sub: var mns = Mynamespace.singleton;
5.6 Branches
5.8 adaptation of the monomer mode
1. You should use monomer mode as much as possible from the point of view of providing namespaces and enhanced modules from code.
2.
JavaScript design mode 5th--Single design mode