这种减少 if 语句中声明的变量范围的模式是一种好习惯吗?
Is this pattern to reduce the scope of variables declared within an if statement a good practice?
我最近看到了这个模式
if(condition) {
(function() {
var foo = "bar";
// do somehing with foo
})();
}
// no more foo
它看起来有点像 hack,我想知道使用这种模式是否是一种好的做法?
如果您想使用闭包根据条件创建私有变量,这可能会很有用。您可能希望分配函数的 return 值,但您可以将此模式用于以下内容:
//conditionally check if we want a counting option
if(counterIsEnabled){
//if we do, create a private count object
var counterObject = (function(){
var count = 0;
//and make it only accessible via a returned method
return {
inc: function(){ count += 1; },
get: function(){ return count}
}
})();
}
它本质上只是有条件地创建一个闭包,如果您想要私有变量和 public accessor/setter 方法来准确控制该变量的访问或更改方式,这将很有用。
这样做意味着没有人可以在不使用您预定义的方法的情况下直接访问 count
变量。
我最近看到了这个模式
if(condition) {
(function() {
var foo = "bar";
// do somehing with foo
})();
}
// no more foo
它看起来有点像 hack,我想知道使用这种模式是否是一种好的做法?
如果您想使用闭包根据条件创建私有变量,这可能会很有用。您可能希望分配函数的 return 值,但您可以将此模式用于以下内容:
//conditionally check if we want a counting option
if(counterIsEnabled){
//if we do, create a private count object
var counterObject = (function(){
var count = 0;
//and make it only accessible via a returned method
return {
inc: function(){ count += 1; },
get: function(){ return count}
}
})();
}
它本质上只是有条件地创建一个闭包,如果您想要私有变量和 public accessor/setter 方法来准确控制该变量的访问或更改方式,这将很有用。
这样做意味着没有人可以在不使用您预定义的方法的情况下直接访问 count
变量。