Home Web Front-end JS Tutorial JavaScript SandBox sandbox design pattern

JavaScript SandBox sandbox design pattern

Nov 28, 2016 pm 03:40 PM
javascript

Sandbox mode is commonly seen in YUI3 core. It is a method that uses the same constructor (Constructor) to generate instance objects that are independent of each other and do not interfere with each other (self-contained), thereby avoiding contamination of the global object.

Namespace

JavaScript itself does not provide a namespace mechanism, so in order to avoid contamination of the global space by different functions, objects, and variable names, the usual approach is to create a unique global object for your application or library, and then Add all methods and properties to this object.

Code Listing 1: Traditional namespace mode

/* 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 = {};
Copy after login

In this code, you create a global object MYAPP and attach all other objects and functions to MYAPP as attributes.

Usually this is a better way to avoid naming conflicts and it is used in many projects, but this method has some disadvantages.

You need to add prefixes to all functions and variables that need to be added.

Because there is only one global object, this means that part of the code can modify the global object arbitrarily and cause the rest of the code to be passively updated.

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 objects. You can also pass a The callback function is used as a parameter. This callback function is an independent sandbox environment where you store your code.

Code Listing 2: Usage of Sandbox

new Sandbox(function(box){
    // your code here...
});
Copy after login

Let us add some other features to the sandbox.

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

The Sandbox() constructor accepts some additional configuration parameters, which define the names of the modules required to generate the object. We want the code to be more modular.

After having the above features, let us 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 need of the 'new' operator.

Code Listing 3: Passing the module name as an array

Sandbox(['ajax', 'event'], function(box){
    // console.log(box);
});
Copy after login

Code Listing 4: Passing the module name as a separate parameter

Sandbox('ajax', 'dom', function(box){
    // console.log(box);
});
Copy after login

Code Listing 5 shows that you can pass the wildcard '*' as a parameter to the constructor, This means calling all available modules. For convenience, if no module name is passed to the constructor as an argument, the constructor will pass '*' as the default argument.

Code Listing 5: Calling the available modules used

Sandbox('*', function(box){
    // console.log(box);
});
Sandbox(function(box){
    // console.log(box);
});
Copy after login

Code Listing 6 shows that you can initialize the sandbox object multiple times, and you can even nest them without worrying about any conflicts with each other.

Code Listing 6: Nested Sandbox Instance

Sandbox('dom', 'event', function(box){
    // work with dom and event
    Sandbox('ajax', function(box) {
    // another sandboxed "box" object
    // this "box" is not the same as
    // the "box" outside this function
    //...
    // done with Ajax
    });
    // no trace of Ajax module here
});
Copy after login

As you can see from the above examples, using the sandbox mode, by wrapping all code logic in a callback function, you can generate different modules based on the required modules. Instances, and these instances work independently without interfering with each other, thereby protecting the global namespace.

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

Adding Modules

Before implementing the main constructor, let’s see 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, where the Key of each pair is The name of the module that needs to be registered, and Value is the entry function of the module. When the constructor is initialized, the current instance will be passed to the entry function as the first parameter, so that the entry function can add additional properties and methods to the instance.

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

Code Listing 7: Registration 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.dettachEvent = function(){};
};
Sandbox.modules.ajax = function(box) {
    box.makeRequest = function() {};
    box.getResponse = function() {};
};
Copy after login

Implementing the constructor

Code Listing 8 describes the method of implementing the constructor, with several key points:

We check whether this is an instance of Sandbox, if not, prove Sandbox If it is not called by the new operator, we will call it again as a constructor.

You can add attributes to this inside the constructor, and you can also add attributes to the prototype of the constructor.

The module name will be passed to the constructor in various forms such as arrays, independent parameters, and the wildcard character '*'.

Please note that in this example we do not need to load modules from external files, but in systems such as YUI3, you can only load the base module (often called a seed), and all other modules will be loaded from external files. loaded in the file.

一旦我们知道了所需的模块,并初始化他们,这意味着调用了每个模块的入口函数。

回调函数作为参数被最后传入构造器,它将使用最新生成的实例并在最后执行。

代码清单8:实现Sandbox构造器

<script>
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 &#39;this&#39; as needed:
    this.a = 1;
    this.b = 2;
    // now add modules to the core &#39;this&#39; object
    // no modules or "*" both mean "use all modules"
    if (!modules || modules === &#39;*&#39;) {
        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;
    }
};
</script>
Copy after login


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

See all articles