Jos*_*eph 49 javascript variables scope if-statement
是否在"if"语句中声明和赋值变量仅在"if"块内或整个函数内可见?
我是否在以下代码中执行此操作?(似乎工作,但多次声明"var结构"似乎很尴尬)任何更清洁的解决方案?
function actionPane(state) {
if(state === "ed") {
var structure = {
"element" : "div",
"attr" : {
"class" : "actionPane"
},
"contains" : [{
"element" : "a",
"attr" : {
"title" : "edit",
"href" : "#",
"class" : "edit"
},
"contains" : ""
}, {
"element" : "a",
"attr" : {
"title" : "delete",
"href" : "#",
"class" : "delete"
},
"contains" : ""
}]
}
} else {
var structure = {
"element" : "div",
"attr" : {
"class" : "actionPane"
},
"contains" : [{
"element" : "a",
"attr" : {
"title" : "save",
"href" : "#",
"class" : "save"
},
"contains" : ""
}, {
"element" : "a",
"attr" : {
"title" : "cancel",
"href" : "#",
"class" : "cancel"
},
"contains" : ""
}]
}
}
return structure;
}
Run Code Online (Sandbox Code Playgroud)
Ove*_*ous 49
1)变量对于整个功能范围是可见的.因此,您应该只声明一次.
2)您不应该在示例中将变量声明两次.我建议在函数顶部声明变量,然后稍后设置值:
function actionPane(state) {
var structure;
if(state === "ed") {
structure = {
...
Run Code Online (Sandbox Code Playgroud)
有关JavaScript的出色反馈,我强烈推荐使用Douglas Crockford的JSLint.它将扫描您的代码以查找常见错误,并找到清理建议.
我还建议阅读小书JavaScript:The Good Parts.它包含许多编写可维护JS代码的技巧.
kar*_*m79 43
JavaScript没有"块作用域",它只有函数作用域 - 因此在if语句(或任何条件块)中声明的变量被"提升"到外部作用域.
if(true) {
var foo = "bar";
}
alert(foo); // "bar"
Run Code Online (Sandbox Code Playgroud)
这实际上描绘了一幅更清晰的画面(并在采访中出现,来自经验:)
var foo = "test";
if(true) {
alert(foo); // Interviewer: "What does this alert?" Answer: "test"
var foo = "bar";
}
alert(foo); // "bar" Interviewer: Why is that? Answer: Because JavaScript does not have block scope
Run Code Online (Sandbox Code Playgroud)
JavaScript中的函数作用域通常是指闭包.
var bar = "heheheh";
var blah = (function() {
var foo = "hello";
alert(bar); // "heheheh"
alert(foo); // "hello" (obviously)
});
blah(); // "heheheh", "hello"
alert(foo); // undefined, no alert
Run Code Online (Sandbox Code Playgroud)
函数的内部范围可以访问包含它的环境,但不能反过来.
为了回答你的第二个问题,可以通过最初构建满足所有条件的"最小"对象,然后根据已经满足的特定条件对其进行扩充或修改来实现优化.
| 归档时间: |
|
| 查看次数: |
48287 次 |
| 最近记录: |