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

Source: Internet
Author: User

The introduction of this article is mainly about the creation of object aspects of the pattern, using a variety of techniques can greatly avoid errors or can write very thin code. The Pattern 1: namespace (namespace) namespace reduces the number of global naming requirements and avoids naming conflicts or excesses. Usually we do this at the object-level definition:varApp = App | |{};app.modulea= App.modulea | |{};app.modulea.submodule= App.moduleA.subModule | |{};app.modulea.submodule.methoda=function() {Console.log ("Print A");}; App.moduleA.subModule.MethodB=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 '); Mode 2: Define dependencies Sometimes one of your modules or functions might refer to some of the third-party modules or tools, so it's best to define these dependent modules at the very beginning so that they can be easily replaced later. varMyFunction =function () {    //Dependent Modules    varevent =YAHOO.util.Event, Dom=YAHOO.util.dom; //The local variables event and Dom are used in the code following the other functions}; Mode 3: Private properties and Private methods JavaScript this book does not provide a specific syntax to support private properties and private methods, but we can implement them by closures, the code is 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 is also about hiding private methods, and in-depth understanding of the JavaScript series (3): The module pattern in the full parse module pattern is a bit similar, but not a return method, but a variable is declared externally, and the variable is internally assigned the public method. 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"));//2Mode 5: Chain mode chain mode you can call a method of an object consecutively, such as Obj.add (1). Remove (2).Delete(4). Add (2in this form, it is very simple to implement the idea of returning 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 (); Summary This is the object creation mode of the previous article, please look forward to tomorrow's next article. Reference: http://shichuan.github.com/javascript-patterns/#object-creation-patternssynchronization and recommendation this article has been synchronized to the directory index: in-depth understanding of JavaScript series in-depth understanding of the JavaScript series, including the original, translation, reprint and other types of articles, if it is useful to you, please recommend supporting a, to the power of the uncle writing. 

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.