Javascript 沙盒模式示例实现

标签 javascript design-patterns sandbox

在 Stoyan Stefanov 的伟大著作“JavaScript 模式”的第 101 页,他解释了沙盒模式。 我非常喜欢他的书,但我真的错过了这里的一些现实生活中的例子,然后才能更好地理解他在说什么。 Like the sandbox pattern!

我正在寻找一个现实生活中的工作实现,例如复制和粘贴起点,只是一个简单的示例,可以帮助您完全理解它。

有没有?

最佳答案

我已经简化了 Stoyan 的例子,试图让它更容易理解正在发生的事情。我也更彻底地评论了它。

/*First define the modules of the sandbox.  These will be defined 
as properties on the constructor function because this is a 
convenient place to keep them.*/

Sandbox.modules = {};

Sandbox.modules.returnNumbers = function(MYAPP) {
    MYAPP.return100 = function() {return 100;};
};

Sandbox.modules.returnLetters = function(MYAPP) {
    MYAPP.returnABC = function() {return "ABC";};
};


function Sandbox() {

    /* Because Sandbox is a constructor, an new object is automatically 
    created.  Because we're in the constructor, we refer to this new object 
    as 'this'. 

    A constructor would typically be used as part of an assignment, e.g. 
    myObject = new Sandbox().  

    However, it's also legitimate javascript to use a constructor without 
    the assignment by just writing new Sandbox() with no assignment.  The 
    constructor does return an object, it's just that it doesn't get 
    assigned to anything so  is discarded.

    We're going to add functionality (methods) to the 'this' object, but 
    rather than returning it, we will pass it to the callback function, so 
    the methods can be used immediately.
    */

    var args = Array.prototype.slice.call(arguments);  //Put the arguments 
    //of the call to the Sandbox constructor in an array called args.

    var callback = args.pop(); //The last argument is the callback
    var requiredmodules = args;  //The remaining arguments are the require
    // modules

    //For each of the modules in 'requiredmodules', add the module's 
    //methods to 'this'
    for (i=0; i< requiredmodules.length; i++) {
        Sandbox.modules[requiredmodules[i]](this);
    }


    //'this' now has methods returnNumbers and returnLetters

    //Call the callback.  In the example below, 'this' will be called 
    //MYAPP, which within the callback will have all the methods from 
    //the required modules.

    callback(this);

}



//Finally here is an example of usage

new Sandbox('returnNumbers', 'returnLetters', function (MYAPP) {

    console.log(MYAPP.return100());
    console.log(MYAPP.returnABC());
});

关于Javascript 沙盒模式示例实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11187582/

相关文章:

javascript - 获取下载 URL 并使其可供其他组件使用

java - 使用 DAO、DTO 模式作为 MVC

linux - 在新用户命名空间中使用 Credential 的 exec.Command 出现错误 : "operation not permitted"

iphone - "Subclassing"Objective-C 中的一个变量

java - .NET中的DDD/聚合

ruby - Ruby 的脚本引擎?

C#:沙箱和性能 (MarshalByRefObject)

javascript - barlasapaydin.com 上的鱼动画

javascript - 从 Javascript 访问 SVG 对象时收到 Uncaught SecurityError

javascript - 如果路径有效,Lodash 返回值数组