In-depth understanding of the JavaScript series (48): object creation mode (next)

Source: Internet
Author: User
Tags hasownproperty

introducing this article is the next chapter in the pattern of creating objects, using a variety of techniques to greatly avoid errors or to write very thin Code. Mode 6: function syntax sugar function syntax sugar is an extension of the method (function) for an object to be quickly added, this is mainly the use of prototype features, the code is relatively simple, we first look at the implementation code:if(typeofFunction.prototype.method!== "function") {Function.prototype.method=function(name, Implementation) { this. prototype[name] =implementation; return  this; };} When you extend an object, you can use This:varperson =function(name) { this. Name =name;}. Method (' GetName ',            function () {                return  this. name; }). Method (' SetName ',function(name) { this. Name =name; return  this;}); This adds the 2 methods of GetName and setname to the person function, and then we'll verify the Results:varA =NewPerson (' Adam '); console.log (a.getname ()); //' Adam 'Console.log (a.setname (' Eve '). getName ());//' Eve 'pattern 7: Object Constants Object constants are the embodiment of various methods that provide set,get,ifdefined in an object, and the method for set only preserves the first set of objects, and the later settings are not valid and have reached the goal that others cannot reload. The implementation code is as Follows:varConstant = (function () {    varConstants ={}, Ownprop=Object.prototype.hasOwnProperty,//only allow setting of these three types of valuesallowed ={string:1, Number:1,            Boolean: 1}, prefix= (math.random () + "_"). Slice (2); return {        //set a property named nameSetfunction(name, Value) {if( this. isDefined (name)) {                return false; }            if(!ownprop.call (allowed,typeofValue)) {                return false; } Constants[prefix+ name] =value; return true; },        //determine if there is a property named nameIsDefined:function(name) {returnOwnprop.call (constants, prefix +name); },        //get a property named nameGetfunction(name) {if( this. isDefined (name)) {                returnConstants[prefix +name]; }            return NULL; }    };} ()); The verification code is as Follows://Check for PresenceConsole.log (constant.isdefined ("maxwidth"));//false//definitionConsole.log (constant.set ("maxwidth", 480));//true//re-detectionConsole.log (constant.isdefined ("maxwidth"));//true//Try redefiningConsole.log (constant.set ("maxwidth", 320));//false//determine if the original definition still existsConsole.log (constant.get ("maxwidth"));//480mode 8: Sandbox mode sandbox mode provides a separate context for one or more modules without affecting the context of other modules, such as a sandbox with 3 methods event,dom,ajax, in which 2 are called to form an environment, and call three composed environments without interference at All. The sandbox implementation code is as Follows:functionSandbox () {//to convert a parameter to an array    varargs =Array.prototype.slice.call (arguments),//the last parameter is callbackcallback =Args.pop (),//other than the last parameter, all the modules to be selectedModules = (args[0] &&typeofargs[0] = = = "string")? Args:args[0], i; //To force the use of the new operator    if(! ( this instanceofSandbox)) {        return NewSandbox (modules, callback); }    //Add Property     this. A = 1;  this. B = 2; //you want to add a module to the this object    //if no module or incoming parameter is "*", it is assumed that all modules are passed in    if(!modules | | modules = = ' * ') {modules= [];  for(iinchsandbox.modules) {if(Sandbox.modules.hasOwnProperty (I)) {modules.push (i); }        }    }    //Initialize the required modules     for(i = 0; I < modules.length; i + = 1) {sandbox.modules[modules[i]] ( this); }    //Call CallbackCallback this);}//Add prototype objects by defaultSandbox.prototype ={name:"My application", Version:"1.0", GetName:function () {        return  this. name; }}; then we define the default initial module: sandbox.modules= {}; Sandbox.modules.dom=function(box) {box.getelement=function () {    }; Box.getstyle=function () {    }; Box.foo= "bar";}; Sandbox.modules.event=function(box) {//access to the Sandbox prototype if Needed:    //BOX.CONSTRUCTOR.PROTOTYPE.M = "mmm";Box.attachevent =function () {    }; Box.detachevent=function () {    };}; Sandbox.modules.ajax=function(box) {box.makerequest=function () {    }; Box.getresponse=function () {    };}; The method is called as Follows://Invocation ModeSandbox ([' Ajax ', ' event '],function(box) {console.log (typeof(box.foo)); //Dom is not selected, so Box.foo does not exist}); Sandbox (' Ajax ', ' Dom ',function(box) {console.log (typeof(box.attachevent)); //No event is selected, so the attachevent defined in the event does not exist .}); Sandbox (‘*‘,function(box) {console.log (box);//all of the methods defined above are accessible}); with three different invocation modes, we can see that the context of three different ways is the same, the first one does not have foo; The second is not attachevent, because only the Ajax and Dom are loaded, and the event is not loaded; The third one loads all of them. Mode 9: static member static members are just static properties provided by a function or object and can be classified as private and public, as in C # or Java. Let's take a look at the public members, the public members are very simple, we usually declare methods, functions are public, such as://constructor FunctionvarGadget =function () {};//public static methodsGadget.isshiny =function () {    return"you bet";};//normal methods added on the prototypeGadget.prototype.setPrice =function(price) { this. Price =price ;};//calling a static methodConsole.log (gadget.isshiny ());//"you bet"//Create an instance, and then call the methodvariphone =NewGadget (); Iphone.setprice (500); Console.log (typeofgadget.setprice);//"undefined"Console.log (typeofiphone.isshiny);//"undefined"Gadget.prototype.isShiny =gadget.isshiny;console.log (iphone.isshiny ());//"you bet"and private static members, we can use its closure characteristics to achieve, the following are two ways to Implement. The first method of Implementation:varGadget = (function () {    //Static Variables/properties    varCounter = 0; //a new implementation of the closure return constructor    return function() {console.log (counter+ = 1); };} ()); //Execute nowvarG1 =NewGadget ();//Logs 1varG2 =NewGadget ();//Logs 2varG3 =NewGadget ();//Logs 3as can be seen, although each time is a new object, but the number is still incremental, to achieve the purpose of static Members. The second way:varGadget = (function () {    //Static Variables/properties    varCounter = 0, newgadget; //New constructor ImplementationNewgadget =function() {counter+ = 1;    }; //methods authorized to accessNewGadget.prototype.getLastId =function () {        returncounter;    }; //overriding Constructors    returnnewgadget;} ()); //Execute nowvariphone =NewGadget (); Iphone.getlastid ();//1varipod =NewGadget (); Ipod.getlastid ();//2varipad =NewGadget (); Ipad.getlastid ();//3the number is also incremented, which is achieved using the closure feature of its internal authorization method. Summary This is the object creation mode of the next chapter, two together a total of 9 patterns, is our daily JavaScript programming often used in the object creation mode, different scenes play a different role, I hope you choose the appropriate model according to their NEEDS. 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 (48): object creation mode (next)

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.