JavaScript中的孤立执行上下文 [英] Isolated execution context in JavaScript

查看:92
本文介绍了JavaScript中的孤立执行上下文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在JavaScript中的空隔离执行上下文中执行一段代码。在下面的示例中,我正在尝试隔离已隔离的执行范围。我想要做的是在没有全局变量的上下文中执行函数。

I'm trying to execute a piece of code within an empty isolated execution context in JavaScript. In the below sample, I'm trying isolate isolated execution scope. What I want to do is to execute a function in context where no global variables are in.

(function() {
  'use strict';

  var scope = Object.create(null);
  var isolated = function() {
    'use strict';
    console.log(document); // Trying to get undefined
                           // but traces `document`.
  };

  isolated.call(scope);
})();

我认为 nullify 全局变量很简单,但是太多了!

I thought it was simple to nullify global variables but there are too many!

var isolated = function(window, document, location /* etc */) {
  // ...
};

isolated.call(scope, undefined, undefined, undefined /* etc */);

有更好的方法吗?

推荐答案

在javascript本身中没有良好的方法(但请参阅Gareth Hayes的另一个选项)。

There is no good way to do this within javascript itself (but see Gareth Hayes answer for another option).

有几种不好的方法。

(function() {
  var scope = Object.create(null);
  var obscurer = {};
  for (var key in this) {
     obscurer[key] = undefined;
  }

  with (obscurer) {
    var isolated = function() {
      'use strict';
      console.log(document);
    };
  }

  isolated.call(scope);
})();

请注意,您实际上会收到错误,因为未定义控制台而不是文档,尽管您可以通过不阻塞obscurer对象中的console来解决这个问题。你可能会发现你需要比你想象的更多的全局变量。

Note that you'll actually get an error because console is not defined rather than document, although you can fix this by not blocking 'console' in the obscurer object. You'll probably find that you need a whole bunch more globals than you realised.

你也只是阻止了窗口的可枚举属性。如果你知道你想要阻止的不可数属性,你必须将它们添加到obscurer。

You're also only blocking the enumerable properties of window. If you become aware of nonenumerable properties that you want to block too, you'll have to add those to obscurer.

当然,使用 意味着你不能再使用严格模式了,每个人都会低头看着你......

Of course, using with means you can't use strict mode any more as well, and everyone will look down their noses at you..

还有更多有趣的事情如果您在节点而不是浏览器中工作,则可用选项。

There are more interesting options available if you are working within node rather than the browser.

这篇关于JavaScript中的孤立执行上下文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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