Introduction
This article mainly introduces the next article on Object creation mode. using various techniques, you can greatly avoid errors or write very conciseCode.
Mode 6: function syntax sugar
Function syntax sugar is an extension to quickly add a method (function) to an object. This mainly utilizes the prototype feature and the code is relatively simple. Let's first look at the implementation code:
If(TypeofFunction. Prototype. method! = "Function") {Function. Prototype. Method=Function(Name, implementation ){This. Prototype [name] =Implementation;Return This;};}
This can be used to extend an object:
VaRPerson =Function(Name ){This. Name =Name;}. Method ('Getname',Function(){Return This. Name;}). Method ('Setname ',Function(Name ){This. Name =Name;Return This;});
In this way, the getname and setname methods are added to the person function. Next, let's verify the result:
VaRA =NewPerson ('Adam'); Console. Log (A. getname ());//'Adam'Console. Log (A. setname ('Eve '). getname ());//'Eve'
Mode 7: Object Constants
Object constants are the embodiment of various methods provided by a set, get, and ifdefined for an object. In addition, only the first set object is retained for the set method, and subsequent settings are invalid, it has reached the goal that others cannot reload. The implementation code is as follows:
VaR Constant = ( Function (){ VaR Constants = {}, Ownprop =Object. Prototype. hasownproperty, // Only values of the three types can be set. Allowed = {String: 1 , Number: 1 , Boolean : 1 }, Prefix = (Math. Random () + "_"). Slice (2 ); Return { // Set the attribute named name Set: Function (Name, value ){ If ( This . Isdefined (name )){ Return False ;} If (! Ownprop. Call (allowed, Typeof Value )){ Return False ;} Constants [prefix + Name] = Value; Return True ;}, // Determine whether an attribute named name exists Isdefined: Function (Name ){ Return Ownprop. Call (constants, prefix + Name );}, // Get the property named name Get:Function (Name ){ If ( This . Isdefined (name )){ Return Constants [prefix + Name];} Return Null ;}};}());
The verification code is as follows:
// Check for existence Console. Log (constant. isdefined ("maxwidth ")); // False // Definition Console. Log (constant. Set ("maxwidth", 480 )); // True // Redetect Console. Log (constant. isdefined ("maxwidth ")); // True // Try to redefine Console. Log (constant. Set ("maxwidth", 320 )); // False // Determine whether the original definition still exists Console. Log (constant. Get ("maxwidth ")); // 480
Mode 8: Sandbox Mode
Sandbox mode provides a separate Context Environment for one or more modules without affecting the Context Environment of other modules. For example, a sandbox contains three method events, dom and Ajax, when two of the calls constitute an environment, there is no interference with the call environment. The Sandbox implementation code is as follows:
Function Sandbox (){ // Convert parameters into Arrays VaR ARGs = Array. Prototype. Slice. Call (arguments ), // The last parameter is callback. Callback =Args. Pop (), // Except the last parameter, all modules are to be selected. Modules = (ARGs [0] & Typeof ARGs [0] = "string ")? ARGs: ARGs [0 ], I; // Use the new operator forcibly If (! ( This Instanceof Sandbox )){ Return New Sandbox (modules, callback );} // Add attribute This . A = 1 ; This . B = 2 ; // Add modules to this object // If there is no module or the input parameter is "*", it indicates that all modules are imported. If (! Modules | modules = '*' ) {Modules = []; For (I In Sandbox. modules ){ If (Sandbox. modules. hasownproperty (I) {modules. Push (I );}}} // Initialize required modules For (I = 0; I <modules. length; I + = 1 ) {Sandbox. modules [modules [I] ( This );} // Call callback Callback (This );} // Add a prototype object by default Sandbox. 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 call method is as follows:
// Call Method Sandbox (['ajax ', 'event'], Function (Box) {console. Log ( Typeof (Box. Foo )); // No Dom is 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 methods defined above can be accessed });
Three different call methods show that the context environments of the three methods are different. foo is not in the first method, and attachevent is not in the second method, because only Ajax and Dom are loaded, but event is not loaded. The third method loads all.
Mode 9: static members
Static members is only a static attribute provided by a function or object. It can be divided into private and public attributes, just like the public static and Private Static attributes in C # or Java.
Let's take a look at the public members. The public members are very simple. The methods we declare at ordinary times, functions are all public, such:
// Constructor VaR Gadget = Function (){}; // Public static method Gadget. isshiny = Function (){ Return "You bet" ;}; // Normal method added on the prototype Gadget. Prototype. setprice = Function (Price ){ This . Price = Price ;}; // Call static methods Console. Log (gadget. isshiny ()); // "You bet" // Create an instance and call the Method VaR IPhone = New Gadget (); iPhone. setprice ( 500 ); Console. Log ( Typeof Gadget. setprice ); // "Undefined" Console. Log ( Typeof IPhone. isshiny ); // "Undefined" Gadget. Prototype. isshiny =Gadget. isshiny; console. Log (iPhone. isshiny ()); // "You bet"
Private Static members can be implemented by using the closure feature. The following are two implementation methods.
The first implementation method:
VaR Gadget = ( Function (){ // Static variables/attributes VaR Counter = 0 ; // New Implementation of the closure return Constructor Return Function () {Console. Log (Counter + = 1 );};}()); // Run now VaR G1 = New Gadget (); // Logs 1 VaR G2 = New Gadget (); // Logs 2 VaR G3 =New Gadget (); // Logs 3
It can be seen that although each object is a new object, the number is still increasing progressively, achieving the goal of static members.
Method 2:
VaR Gadget = ( Function (){ // Static variables/attributes VaR Counter = 0 , Newgadget; // New constructor implementation Newgadget = Function () {Counter + = 1 ;}; // Authorization of accessible methods Newgadget. Prototype. getlastid = Function (){ Return Counter ;}; // Override Constructor Return Newgadget ;}()); // Run now VaR IPhone = New Gadget (); iPhone. getlastid (); // 1 VaR IPod = New Gadget (); iPod. getlastid (); // 2 VaR IPad = New Gadget (); iPad. getlastid (); // 3
The number is also increasing, which is achieved by using the closure feature of its internal authorization method.
Summary
This is the next article on the object creation mode. The two articles have nine modes in total. They are the object creation mode that we often use in daily JavaScript programming. Different scenarios play different roles, we hope you can select the applicable mode based on your needs.
Reference: http://shichuan.github.com/javascript-patterns/#object-creation-patterns
Reprinted:
Uncle Tom