JavaScript creates an object's singleton, factory, constructor mode

Source: Internet
Author: User

01 Single-Case mode

First look at a problem, we want to describe two people in the program, these two people have names and age, may just start to learn JS will be written as follows:

1 var name1 = ' Iceman '; 2 var age1 =; 3 4 var name2 = ' Mengzhe '; 5 var age2 = 26;

The above is a description of two people, everyone has a name and age, but everyone's name and age are not put together, that is, each person's age and name does not correspond. At this point we draw the concept of the object: To put the properties and methods that describe the same thing (the same object) under the same memory space, play the role of grouping, so that the properties between different things, even if the property names are identical to each other will not conflict.

1 var person1 = {2     name: ' Iceman ',3     age:25}; 4 5 var person2 = {6     name: ' Mengzhe ',7     age:26};

The above can be thought of as a grouping of code-writing patterns, through such a grouping, each person's name and age are in the same memory space, that is, each person's name and age correspond. We also call this pattern of grouping code a singleton pattern (also called the object literal pattern in JavaScript advanced programming), where Person1 and Person2 are called Namespaces in Singleton mode.

The singleton mode is a kind of pattern that is used frequently in project development, because we can use the singleton pattern to develop the module, for a relatively large project, need many people collaborative development, so the general situation will be based on the current project needs, divided into several functional modules, each person is responsible for part, while developing, Finally, everyone's code is merged, such as:

public Modules: providing public methods

1 var utils = {2   Select:function  () {3       /// ... 4   }5 };

Page Tab module: Implementing tab switching

1 var tabmodule = {2 change   :function  () {3       /// ways to downgrade a different namespace in your own namespace 4   }5 };

Search module: Implementation of changes in search content processing

 1  var  searchmodule = { 2  change:function   () { 3   This . Clickevent (); //  4  },  5  clickevent:function   () { 6  //  ...  7  }  8  };

In the example above, there is a change method in both the tab module (tabmodule) and the Search module (searchmodule), and if no sub-modules are written it will cause a naming conflict, according to the parsing rules of the JavaScript language, The method declared later overrides the method previously declared. After the module partition, the change method under the two modules belongs to the respective modules, and the call is called by the method under the module (Tabmodule.change (), Searchmodule.change ()), there is no conflict.

02 Factory mode

Review the Singleton pattern:
 1  var  person1 =  { 2  name: ' Iceman '  6  }  7  };  8  Person1.writejs (); 

Singleton mode solves the problem of grouping, so that each object has its own independent namespace, but not mass production, each new object will have to re-write a copy of the exact same code. At this time there is the Factory mode, that is: the implementation of the same thing the same code, put into a function, and later if you want to implement this function, you do not need to rewrite the code, as long as the current function can be executed, this is the function of the package, reflecting the high cohesion, low-coupling idea: Reduce the page of redundant code Increase the reuse of code:

1 functionCreateperson (name, age) {2     varobj = {};3Obj.name =name;4Obj.age =Age ;5Obj.writejs =function () {6Console.log ( This. Name + ' Write JS ');7}returnobj;8 }9 Ten varP1 = Createperson (' Mengzhe ', 26); One P1.writejs (); A  - varP2 = Createperson (' Iceman ', 25); -P2.writejs ();

By the way, overloading: In Java, C # and other strongly typed object-oriented programming languages, there is the concept of function overloading, but there is no overload in JavaScript, if the method name is the same, the following will overwrite the front, and finally only one method of the definition, However, we can implement the function of simulating overloading according to the parameters passed:

1 function sum (num) {    if (typeof num = = = ' undefined ') {        return 0; 2     }    return num; 3 }4 sum (+); 5 sum ();

03 constructor Mode

1 functionCreatejsperson (name, age) {2      This. Name =name;3      This. Age =Age ;4      This. Writejs =function () {5Console.log ( This. Name + ' Write JS ');6     }7     //The browser then returns the created instance by default8 }9 varP1 =NewCreatejsperson (' Iceman ', 25);Ten P1.writejs (); One varP2 =NewCreatejsperson (' Mengzhe ', 26); AP2.writejs ();

Note: The above is new Createjsperson (' Iceman ', 25) This way, the object is created using new, which differs from the normal invocation of the function:

1 var res = Createjsperson (' xx ', 7);

This does not call the function directly with new, not the constructor but the normal function, because there is no write return, so res=undefined, and Createjsperson This method is the window.

The purpose of the constructor pattern is to create a custom class and create an instance of the class.

The difference between the pattern of the constructor pattern and the normal function:

At the time of execution

    • normal function execution: Createjsperson ()

    • Constructor execution: New Createjsperson (), once executed by new, Createjsperson is a class, and the return value of the function is an instance of the Createjsperson class.

At the time of the function code execution

    • The same: both form a private scope and then experience: Parameter assignment--pre-interpretation--code executes from top to bottom (classes are executed like normal functions, and it also has a side of normal functions).

    • Different: ① before the code of the constructor is executed, the browser will create a value of the object data type by default (the value of this object type is actually an instance of the current class) without having to manually create the object yourself; ② the next code executes from top to bottom, The principal that is executed as the current instance (this represents the current instance), then assigns the property name and the attribute value to the current instance respectively; ③ Finally, the browser will return the created instance by default.

Note the point:

    • All of the classes in JavaScript are function data types, which become a class through new execution, but it is also a normal function.

    • All instances of JavaScript are object data types;

    • In the constructor pattern, the this.xx = XX in the class (in the function body) is an instance of the current class;

    • P1 and P2 are Createperson instances of this class, so they all have writejs, but the methods between the different instances are not the same, and the attribute added to the instance in the Class (this.xxx=xxx) belongs to the private property of the current instance. The instances and instances are separate individuals, so private attributes are not equal.

      1 // -- false



JavaScript creates an object's singleton, factory, constructor mode

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.