javascript沙箱一个模块以防止引用Window [英] javascript sandbox a module to prevent reference to Window

查看:53
本文介绍了javascript沙箱一个模块以防止引用Window的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个沙盒模块,它可以接受一个对象并阻止该对象对 window 的代码引用.

I trying to create a sandbox module that can take a object and prevent that object's code reference to window.

这是它在概念上的工作方式.

here is how it work in concept.

var sand = function(window) {
var module = {
    say: function() {
        console.log(window.location);
    }   
};
return module;
}
sand({}).say(); // window.location is undefine

如果对象是传入的,这不起作用

This doesn't work if the object is pass-in

var $sand = (function(){
return function(obj, context) {
    return (function(obj, window) {
        window.module = {};
        // doesn't work even copy object
        for (p in obj) {
            window.module[p] = obj[p];
        }
        console.log(window.location); // undefine
        return window.module;
    }(obj, context));
};
}());

var module = {
say: function() {
    console.log(window.location);
}
};

$sand(module, {}).say(); // still reference to window.location

我怎样才能使这个模式起作用?

How can i make this pattern work?

推荐答案

在你的第一个例子中,window 是 undefined 的唯一原因是因为你传入一个空对象并调用参数 window,所以它隐藏了真正的window.

In your first example, the only reason window is undefined is because you are passing in an empty object and calling the argument window, so it is hiding the real window.

此外,您始终可以通过在闭包中提升 this 变量来访问 window 对象,如下所示:

Also, you can always get access to the window object by hoisting the this variable inside a closure, like so:

console.log ( ( function () { return this; } )() );

因此,即使您以某种方式设法阻止了 window,再次将其恢复也很简单.

So even if you somehow manage to block window, it's trivial to get it back again.

这篇关于javascript沙箱一个模块以防止引用Window的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆