开发者

Run function in closed environment

How can I run code so that the code itself cannot access my main code on the window variable?

For example, I would want:

var popup = function(msg){ alert(msg); };

(function(){
    window.x = 5;
    popup("hi."); //does not work
})();

alert(x) //does not return 5

I'm trying to write a code tester. I've been reading about scopes and classes, but I'm not understanding them enough to figure 开发者_如何学Pythonthis out.


The short answer is that you can't prevent a piece of JavaScript code from accessing global variables. This is why they're called 'global' and one of the many reasons JS programmers insist on properly scoped variables.

A slightly longer answer,

Your example is confusing because in your code comments you say "does not work" when what I think you mean is "I don't want this to work, but it does".

In JavaScript closures 'close' over the scope in which they were declared.

The JS runtime looks up variable references inside the current scope first and if the reference isn't found it'll look up the variable reference in the parent scope, the parent of the parent scope, etc until there is a scope with no ancestor. Finally it will look up the reference in the Global scope (which in browsers corresponds to the window scope). This is why variables in window scope are accessible from everywhere.

There is an additional quirk in JavaScript that when a variable is referenced but hasn't been declared (via the var keyword) the variable is automatically created in the Global scope. JS would be a better language if this wasn't the case, but that's a different story.

I'm not sure what kind of testing suite you want to build but I'm fairly certain that you have to enforce a little bit of QA by not allowing arbitrary Global assignment in the code-to-be-tested, which is a really more than a best-practice these days.

One way to do that which I used in a previous project is to enumerate the properties in the Global scope before running the code-to-be-tested and matching this list to the list after loading the code and after each execution. A new Global variable appearing is then an automatic test fail.


Variables defined in window are global. If you don't want them to be accessible, don't define them globally.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜