JavaScript design mode Security Sandbox Mode

Source: Internet
Author: User

Namespace

JavaScript itself does not provide a namespace mechanism. To avoid global space pollution caused by different functions, objects, and variable names, the common practice is to create a unique global object for your application or library, and then add all methods and attributes to this object.
Copy codeThe Code is as follows:
/* BEFORE: 5 globals */
// Constructors
Function Parent (){}
Function Child (){}
// A variable
Var some_var = 1;
// Some objects
Var module1 = {};
Module1.data = {a: 1, B: 2 };
Var module2 = {};
/* AFTER: 1 global */
// Global object
Var MYAPP = {};
// Constructors
MYAPP. Parent = function (){};
MYAPP. Child = function (){};
// A variable
MYAPP. some_var = 1;
// An object
MYAPP. modules = {};
// Nested objects
MYAPP. modules. module1 = {};
MYAPP. modules. module1.data = {a: 1, B: 2 };
MYAPP. modules. module2 = {};

Code List 1: Traditional namespace Mode


In this Code, you have created a global object MYAPP and attached all other objects and functions as attributes to MYAPP.

This is usually a better way to avoid name conflicts. It is applied to many projects, but this method has some disadvantages.

1. You need to add a prefix to all functions and variables to be added.
2. Because there is only one global object, this means that some code can modify the global object without authorization, resulting in passive update of other codes.

Global Constructor

You can use a global constructor instead of a Global Object. We name this constructor Sandbox (). You can use this constructor to create an object, you can also pass a callback function as a parameter for the constructor, which is an independent sandbox environment where you store code.
Copy codeThe Code is as follows:
New Sandbox (function (box ){
// Your code here...
});

Code List 2: Sandbox usage


Let's add some other features to the sandbox.


1. You can create a sandbox without using the 'new' operator.

2. The Sandbox () constructor accepts some additional configuration parameters that define the name of the module required for generating the object, and we want the code to be more modular.


With the above features, let's see how to initialize an object.


Code listing 3 shows that you can create an object that calls the 'ajax 'and 'event' modules without the 'new' operator.


Copy codeThe Code is as follows:
Sandbox (['ajax ', 'event'], function (box ){
// Console. log (box );
});

Code List 3: Passing module names in the form of Arrays
Copy codeThe Code is as follows:
Sandbox ('ajax ', 'dom', function (box ){
// Console. log (box );
});

Code list 4: Passing module names as independent parameters

Code List 5 shows that you can pass the wildcard '*' as a parameter to the constructor, which means to call all available modules for convenience, if no module name is passed as a parameter to the constructor, the constructor uses '*' as the default parameter.

Copy codeThe Code is as follows:
Sandbox ('*', function (box ){
// Console. log (box );
});
Sandbox (function (box ){
// Console. log (box );
});

Code List 5: available modules used for calling


Code Listing 6 shows that you can initialize sandbox objects multiple times, or even nest them without worrying about any conflict between them.
Copy codeThe Code is as follows:
Sandbox ('dom ', 'event', function (box ){
// Work with dom and event
Sandbox ('ajax ', function (box ){
// Another sandboxed "box" object
// This "box" is not the same
// The "box" outside this function
//...
// Done with Ajax
});
// No trace of Ajax module here
});

Code List 6: Nested sandbox instances

From the above examples, we can see that the sandbox mode is used to wrap all the code logic in a callback function. You can generate different instances based on different modules, these instances do not interfere with each other and work independently, thus protecting the global namespace.

Now let's see how to implement this Sandbox () constructor.


Add Module

Before implementing the main constructor, let's take a look at how to add modules to the Sandbox () constructor.

Because the Sandbox () constructor function is also an object, you can add an attribute named 'modules' to it. This attribute will be an object containing a set of key-value pairs, each Key-Value pair is the module name to be registered, and Value is the entry function of the module, when the constructor initializes, the current instance will be passed to the entry function as the first parameter, so that the entry function can add additional attributes and methods for the instance.

In code listing 7, we added the 'dom ', 'event', and 'ajax' modules.

Copy codeThe Code is as follows:
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. dettachEvent = function (){};
};
Sandbox. modules. ajax = function (box ){
Box. makeRequest = function (){};
Box. getResponse = function (){};
};

Code List 7: Registration Module


Implementation Constructor

Code listing 8 describes how to implement the constructor. The key points are as follows:

1. check whether this is a Sandbox instance. If not, it proves that Sandbox is not called by the new operator. We will re-call it as a constructor.
2. You can add properties for this in the constructor, or you can add properties for the constructor prototype.
3. The module name is passed to the constructor in the form of arrays, independent parameters, and wildcards.
4. note that in this example, we do not need to load modules from external files, but in YUI3, you can only load basic modules (usually called seed )), all other modules are loaded from external files.
5. Once we know the required modules and initialize them, this means that the entry functions of each module are called.
6. The callback function is finally passed into the constructor as a parameter. It uses the newly generated instance and runs it at the end.
Copy codeThe Code is as follows:
Function Sandbox (){
// Turning arguments into an array
Var args = Array. prototype. slice. call (arguments ),
// The last argument is the callback
Callback = args. pop (),
// Modules can be passed as an array or as individual 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 'others' as needed:
This. a = 1;
This. B = 2;
// Now add modules to the core 'it' object
// No modules or "*" both mean "use all modules"
If (! Modules | modules = '*'){
Modules = [];
For (I in Sandbox. modules ){
If (Sandbox. modules. hasOwnProperty (I )){
Modules. push (I );
}
}
}
// Init the required modules
For (I = 0; I <modules. length; I ++ ){
Sandbox. modules [modules [I] (this );
}
// Call the callback
Callback (this );
}
// Any prototype properties as needed
Sandbox. prototype = {
Name: "My Application ",
Version: "1.0 ",
GetName: function (){
Return this. name;
}
};

Code List 8: implement the Sandbox Constructor
Source: Stoyan Stefanov-JavaScript Patterns Part 7: The Sandbox Pattern

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.