[英]Prevent function from looking for variables in outer scopes
我想这样做是因为我的项目通常使用如下的快捷变量:
(function() {
var world = new World(),
Event = world.Event,
Guide = world.Guide;
Event.add('updateUI', function() {
// 1st: Correct, the value of 'this' refers to a world
this.Guide.show('UI updated');
// 2nd: Ok because 'world' was defined in outer scope
world.Guide.show('UI updated');
// 3rd: Ok because 'Guide' was defined in outer scope
Guide.show('UI updated');
});
})();
如果我移动Event.add('updateUI', function() { ... });
到其他文件,只有第一个语句( this.Guide.show
)有效。 如何防止此函数使用外部作用域的world
或Guide
变量,以便第二个和第三个语句从头开始抛出错误。
use strict
与此非常接近,但它只能阻止您获取对全局对象的访问权限。
更新以使此问题更清楚:主要问题是:是否有任何方法可以阻止函数在外部作用域中查找变量? 如果没有办法,请解释原因,因为我认为这是合理的需要。
你可以使用阴影。 如果在函数内部显式声明变量(而不是初始化它),函数将使用此变量而不是外部作用域中的同名变量。
例:
var outer = 'foo';
function isolated () {
var outer;
console.log(outer);
};
isolated(); // output undefined
这应该涵盖您的需求。
还有另一种方法,但它是一个丑陋的黑客,可能不适用于某些浏览器(IE?)。
这是一个例子:
var outer = 'foo';
function isolated () {
console.log(outer);
};
var e = eval;
// will throw exception: 'outer' is not defined
console.log(e('('+isolated.toString()+')()'));
eval
和e
不完全相同。 'true'eval可以访问整个范围,但是如果你复制它,那么javascript引擎可以通过不使外部范围可用于经过验证的代码来优化它。
但是: 不要那样做 !
eval
,它会使调试成为一场噩梦(你无法访问有用的堆栈跟踪),存在性能和安全问题,并且你很快就会得到一个糟糕的代码来维护。 不知道你为什么要这样做,但使用简短的例子:
(function(theFunk) {
var world = new World(),
Event = world.Event,
Guide = world.Guide;
Event.add('updateUI',theFunk);
})(function(){
this.Guide.show('UI updated'); // 1st: depends on what you do with it
world.Guide.show('UI updated'); // 2nd: will fail (depends on global)
Guide.show('UI updated'); // 3rd: will fail (depends on global)
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.