隔离外部Javascript并防止污染?

时间:2013-06-03 16:13:55

标签: javascript closures

我从一个特定的游戏中获得了一些机器生成的Javascript,这个应用程序对闭包不起作用。我试过像这样包装整个事情:

var gameInstance = (function() {

    // Some code that defines stuff

    return {
        initGame: function() {
            _VD1();
        }
     }
})()

我正在寻找一种方法来防止它泄漏到全局命名空间中,然后能够清理整个游戏。这种特殊类型的Closure似乎仍然导致许多功能的泄漏。它隐藏了一些像_VD1调用的东西 - 但其他东西仍然设法泄漏。我可以注意什么/做什么来防止这种情况?

3 个答案:

答案 0 :(得分:3)

听起来你正在使用的代码是在不使用var关键字的情况下声明了很多变量。

您可以使用var关键字在最外层函数范围的顶部使用变量来声明所有变量。

如果根本无法修改其他脚本,除了确保所有自己的脚本都正确命名空间之外,没有什么可以做的,这样它们就不会受到所有全局变量的干扰。脚本正在声明/修改。

答案 1 :(得分:0)

听起来你正试图保留一些沙盒的javascript,有可能使用iframe实现这一点。这是未经测试的,但可以作为灵感;

var sb = document.createElement('iframe');
document.body.appendChild(sb);
sb.document.write('
<html>
<head></head>
<body>
<script>
gameInstance = (function() {

    // Some code that defines stuff

    return {
        initGame: function() {
            _VD1();
        }
     }
})()

</script>
</body>
</html>');

var gameInstance = sb.gameInstance;

答案 2 :(得分:0)

也许http://jqueryboilerplate.com/为你提供灵感

// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
;(function ( $, window, document, undefined ) {

})( jQuery, window, document );