JavaScript Basic object creation mode sandbox mode (026)

Source: Internet
Author: User

Sandbox mode can compensate for two deficiencies in the namespace pattern:

    • Using a unique global object as a global variable entry for a program makes it impossible to use two different versions of the API in the same program, so they use the same unique global object name, such as MyApp;
    • Longer nested objects make code writing and parsing slower;
Sandbox mode, as its name says, provides an environment in which modules can "play" together, with no interaction between the modules and the sandbox. This pattern is used extensively in YUI3. Here's how a sandbox pattern is implemented: 1. Global ConstructorsThere is only one global object in the namespace pattern; in sandbox mode, the only one is a global constructor: sandbox (), for example. The sandbox is just the name used in this example, and the program should use a name that has a specific meaning. This global constructor takes a callback function and provides the sandbox environment for this callback function. The call to the sandbox constructor is probably this:
New Sandbox (function (box) {    //Your code here ...});
The object box, like MyApp in namespace mode, provides the functionality required in the library. Then add two techniques to the sandbox mode: Use the previous check method to ensure that the sandbox constructor is always called with new, and the sandbox constructor accepts parameters to tell what modules are available in the sandbox. With these two techniques,we will check that the sandbox () is not called with new, and then use new to invoke itself in the sandbox (): Make sure it is always called with new, and pass in the appropriate parameters to inform the sandbox to provide the appropriate functionality. Thus, the invocation of Sanbox () becomes the same:
Sandbox ([' Ajax ', ' event '], function (box) {    //console.log (box);});
You can also use two (or more) parameters to pass the name of the function module that you want to provide in the sandbox into a sandbox function:
Sandbox (' Ajax ', ' Dom ', function (box) {    //console.log (box);});
If there are many modules in the program and you want to support all modules at once, you can use "*" instead of all the module names, or, more simply, omit the parameter of the module name to indicate that all modules are required:
Sandbox (' * ', function (box) {    //console.log (box);}); Sandbox (box) {    //console.log (box);});
The sandbox mode should be flexible enough to support the use of the sandbox function again in the sandbox's callback function:
Sandbox (' Dom ', ' event ', function (box) {    //work with Dom and event    Sandbox (' Ajax ', function (box) {       //anothe R sandboxed "box" Object       //This "box" was not the same as       //the ' box ' outside this function//       ...       Done with Ajax    });    No trace of Ajax module here});
The above exampleThe idea is to tell the sandbox function the name of the required function module and write the code snippet in the callback function. This allows you to provide the required module functionality support to different code snippets without creating a global variable pollution. the objects created by the sandbox () are independent of each other and depend on different function modules. In addition, since the sandbox is a function, it is also an object, so you can add static properties to the sandbox () to hold some data. 2. Defining the moduleBefore introducing the sandbox implementation, let's look at how to define the module. In sandbox mode, the global constructor sandbox is a function object, so you can add a static property to it to save each module, such as modules. Modules is a member of the Sandbox property, is also an object, it through the internal key-value pairs to save the module, the key as the module name, and the value is the implementation of the module. The procedure for defining a module is this:
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.prototyp E.M = "MMM";    Box.attachevent = function () {};    Box.dettachevent = function () {};}; Sandbox.modules.ajax = function (box) {    box.makerequest = function () {};    Box.getresponse = function () {};};

In the above example, we have added three modules to the Modules object, namely, Dom,event, and Ajax. 3. Sand table constructor for the sandboxA viable sandbox constructor is this (in fact, you might need to change the sandbox to a meaningful name in your program):
function Sandbox () {//turning arguments into an array var args = Array.prototype.slice.call (arguments), The last argument was the callback callback = Args.pop (),//modules can be passed as an array or as Indi Vidual Parameters modules = (Args[0] && typeof args[0] = = = "string")?    Args:args[0], I; Make sure the function is called//as a constructor if (! (    This instanceof sandbox) {return new sandbox (modules, callback);    }//Add properties to ' this ' as NEEDED:THIS.A = 1;    this.b = 2; Now add modules to the core ' this ' object//No modules or "*" both mean "use all modules" if (!modules | | module        s = = = ' * ') {modules = [];            For (i in Sandbox.modules) {if (Sandbox.modules.hasOwnProperty (i)) {Modules.push (i); }}}//Initialize the required modules for (i = 0; i < modules.length; i + = 1) {Sandbox.mo Dules[modules[I]]    (this); }//Call the callback callback (this);} Any prototype properties as Neededsandbox.prototype = {name: "My Application", Version: "1.0", getname:funct    Ion () {return this.name; }};

Key elements of the above implementation include:
    • Check if this is a sandbox instance, and if not (stating that the sandbox () is not called with new), use new to call the sandbox again;
    • You can add properties to the constructor using this, or you can add attributes by prototype;
    • Modules that need to be used can be passed through an array of module names, or they can be passed in as a module name for each parameter, and "*" matches all supported modules (the JS file that defines the required modules can also be introduced in the actual use);
    • If the required module is already defined, initialize it, i.e. execute the function that defines the module;
    • The last parameter of the sandbox function is a callback function that is called at the end of the sandbox function and executes the corresponding code using the object created by the sandbox, which is like running in a sandbox: they get the modules they need to support and are isolated from the external code.

JavaScript Basic object creation mode sandbox mode (026)

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.