In-depth understanding of the JavaScript series (47): Object creation mode (previous)

Source: Internet
Author: User

Introduced

This article is mainly about the creation of object-oriented patterns, using a variety of techniques can greatly avoid errors or can write very thin code.

Pattern 1: Namespace (namespace)

Namespaces can reduce the number of global naming requirements and avoid naming conflicts or excesses. Usually we do this at the object-level definition:

var  app = App | |  {};app.modulea  = App.modulea | |  {};app.modulea.submodule  = App.moduleA.subModule | |  {};app.modulea.submodule.methoda  = function   () {Console.log (" Print A " = function   () {Console.log ( "Print B"  

If there's a lot of hierarchy, it's going to have to go on like this, it's chaos. namespace pattern is to solve this problem and exist, we look at the code:

//Unsafe , may overwrite an existing MyApp objectvarMYAPP = {};//Okayif(typeofMYAPP = = = "undefined") {    varMYAPP = {};}//in a more concise wayvarMyApp = MyApp | | {};//defining a common methodMyapp.namespace =function(ns_string) {varParts = Ns_string.split ('. ')), Parent=MYAPP, I; //default if the first node is MyApp, it is 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 a        if(typeofParent[parts[i]] = = = "undefined") {Parent[parts[i]]= {}; } Parent=Parent[parts[i]]; }    returnparent;};

The calling code is very simple:

//after namespace, you can assign the return value to a local variablevarModule2 = Myapp.namespace (' MYAPP.modules.module2 ')); Console.log (Module2= = = MYAPP.modules.module2);//true//Skip MyAppMyapp.namespace (' Modules.module51 ');//very long name.Myapp.namespace (' Once.upon.a.time.there.was.this.long.nested.property ');
Pattern 2: Defining dependencies

Sometimes one of your modules or functions may refer to some of the third-party modules or tools, it is better to have these dependent modules at the beginning of the definition, so that later can be easily replaced.

var function () {    //  dependent module    var event = YAHOO.util.Event,        =  YAHOO.util.dom;     // The local variables event and Dom} are used in the code following the other functions;
Pattern 3: Private properties and Private methods

JavaScript does not provide a specific syntax to support private properties and private methods, but we can implement them by closures, as follows:

functionGadget () {//Private Objects    varname = ' IPod '; //Public Functions     This. GetName =function () {        returnname; };}varToy =NewGadget ();//name not defined, is privateConsole.log (Toy.name);//undefined//Public method Access nameConsole.log (Toy.getname ());//"IPod"varMyObj//assigning values to myobj by self-executing functions(function () {    //Free Objects    varName = "My, Oh My"; //the public part is implemented, so there is no VarMyObj = {        //Authorization MethodGetName:function () {            returnname; }    };} ());
Mode 4:revelation mode

It is also about the pattern of hiding private methods, and the module pattern in the in-depth understanding of the JavaScript series (3): Fully parsed module mode is a bit similar, but not a return method, but a variable is declared externally, and then the variable is assigned the public method internally. The code is as follows:

varmyarray; (function () {    varASTR = "[Object Array]", ToString=Object.prototype.toString; functionIsArray (a) {returnTostring.call (a) = = =Astr; }    functionindexOf (haystack, needle) {vari = 0, Max=haystack.length;  for(; i < max; i + = 1) {            if(Haystack[i] = = =needle) {                returni; }        }        return-1; }    //all the details above are hidden by the way of assignment .MyArray ={isarray:isarray, indexof:indexof, inarray:indexof};} ());//Test CodeConsole.log (Myarray.isarray ([1, 2]));//trueConsole.log (Myarray.isarray ({0:1}));//falseConsole.log (Myarray.indexof (["A", "B", "Z"], "Z"));//2Console.log (Myarray.inarray (["A", "B", "Z"], "Z"));//2Myarray.indexof=NULL; Console.log (Myarray.inarray (["A", "B", "Z"], "Z"));//2
Mode 5: Chain mode

Chain mode allows you to invoke a method of an object consecutively, such as Obj.add (1). Remove (2). Delete (4). Add (2) This form, the implementation of the idea is very simple, is to return this as is. The code is as follows:

varobj ={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 InvocationObj.increment (). Add (3). Shout ();//5//You can also call a singleobj.increment (); Obj.add (3); Obj.shout ();

Copyright NOTICE: This article for Bo Master http://www.zuiniusn.com original article, without Bo Master permission not reproduced.

In-depth understanding of the JavaScript series (47): Object creation mode (previous)

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.