In-depth understanding of JavaScript series (47): Object creation mode (Part 1)

Source: Internet
Author: User
Introduction

This article mainly describes how to create objects. using various techniques, you can avoid errors or write very compact objects.Code.

Mode 1: namespace)

The namespace can reduce the number of global names required to avoid name conflicts or excessive. This is often the case when we define the object hierarchy:

 
VaRAPP = app |{}; App. modulea= App. modulea |{}; App. modulea. submodule= App. modulea. submodule |{}; App. modulea. submodule. methoda=Function() {Console. Log ("Print") ;}; App. modulea. submodule. methodb=Function() {Console. Log ("Print B");};

If there are many layers, it will continue like this and it is very messy. The namespace mode exists to solve this problem. Let's look at the Code:

//  Insecure, may overwrite existing MyApp objects   VaR MyApp = {};  //  Okay   If ( Typeof MyApp = "undefined" ){  VaR MyApp = {};}  //  More concise method   VaR MyApp = MyApp | {}; //  Define common methods MyApp. namespace = Function  (Ns_string ){  VaR Parts = ns_string.split ('.' ), Parent = MyApp, I;  //  If the first node is MyApp by default, it will be ignored, such as MyApp. modulea.       If (Parts [0] === "MyApp" ) {Parts = Parts. Slice (1 );}  For (I = 0; I <parts. length; I + = 1 ){  //  If the property does not exist, create           If ( Typeof Parent [parts [I] === "undefined" ) {Parent [parts [I] = {};} Parent = Parent [parts [I];}  Return  Parent ;}; 

The call code is very simple:

//After using namespace, you can assign the return value to a local variable. VaRModule2 = MyApp. namespace ('myapp. modules. module2'); Console. Log (module2=== MyApp. modules. module2 );//True//Skip MyAppMyApp. namespace ('Les Les. lele51');//Very Long NameMyApp. namespace ('Once. Upon. A. Time. There. Was. This. Long. nested. properties ');

Mode 2: define dependency

Sometimes a module or function may reference some third-party modules or tools. At this time, it is best to define these dependent modules at the beginning, this can be easily replaced in the future.

VaRMyfunction =Function(){//Dependency ModuleVaREvent =Yahoo. util. event, Dom=Yahoo. util. Dom;//Use the local variables event and Dom in the code behind other functions};

Mode 3: Private attributes and private methods

Javascript book does not provide specific syntax to support private attributes and private methods, but we can implement it through closures. The Code is as follows:

 Function  Gadget (){  //  Private object       VaR Name = 'ipod';  //  Public Functions       This . Getname = Function  (){  Return  Name ;};}  VaR Toy = New  Gadget ();  //  The name is undefined and is private. Console. Log (toy. Name ); //  Undefined   //  Public method access name Console. Log (toy. getname ()); //  "IPod"    VaR Myobj; //  Assign values to myobj using the self-executed Function ( Function  (){  //  Free object       VaR Name = "My, oh my" ;  //  Implemented the public part, so there is no VaR Myobj = {  //  Authorization Method Getname: Function  (){  Return  Name ;}};}()); 

Mode 4: Revelation Mode

The Mode for hiding private methods is similar to the module mode in "Deeply Understanding JavaScript series (3): Fully parsing module mode", but it is not the return mode, instead, declare a variable externally and assign a public method to the variable internally. The Code is as follows:

 VaR  Myarray ;(  Function  (){  VaR Astr = "[object array]" , Tostring = Object. Prototype. tostring;  Function  Isarray (){  Return Tostring. Call (A) = Astr ;}  Function  Indexof (haystack, needle ){  VaR I = 0 , Max = Haystack. length;  For (; I <Max; I + = 1){  If (Haystack [I] = Needle ){  Return  I ;}}  Return -1 ;}  //  By assigning values, all the above details are hidden. Myarray = {Isarray: isarray, indexof: indexof, inarray: indexof };}());  //  Test code Console. Log (myarray. isarray ([1, 2]);//  True Console. Log (myarray. isarray ({0: 1 })); //  False Console. Log (myarray. indexof (["A", "B", "Z"], "Z ")); //  2 Console. Log (myarray. inarray (["A", "B", "Z"], "Z ")); //  2   Myarray. indexof = Null  ; Console. Log (myarray. inarray ([ "A", "B", "Z"], "Z ")); //  2 

Mode 5: Chain Mode

In the chain mode, you can call methods of an object consecutively, such as obj. add (1 ). remove (2 ). delete (4 ). in the form of add (2), the Implementation idea is very simple, that is, to return this as is. The Code is as follows:

 VaR OBJ = {Value: 1 , Increment:  Function  (){  This . Value + = 1 ;  Return   This  ;}, Add:  Function  (V ){ This . Value + = V;  Return   This  ;}, Shout:  Function  () {Console. Log (  This  . Value );}};  //  Chain Method call OBJ. increment (). Add (3). Shout (); //  5    //  It can also be called one by one  OBJ. increment (); obj. Add ( 3 ); Obj. Shout (); 

Summary

This article is the first article on Object creation mode. We look forward to the next article tomorrow.

Reference: http://shichuan.github.com/javascript-patterns/#object-creation-patterns

 

Transferred from:

Uncle Tom

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.