在“if”语句中声明和赋值的变量是仅在“if”块中还是在整个函数内可见?
我是否在以下代码中执行此操作? (似乎有效,但多次声明“var structure”似乎很尴尬)任何更清洁的解决方案?
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;
}
答案 0 :(得分:45)
1)Variables are visible for the whole function scope。因此,您只应声明一次。
2)你不应该在你的例子中两次声明变量。我建议在函数顶部声明变量,然后稍后设置值:
function actionPane(state) {
var structure;
if(state === "ed") {
structure = {
...
对于关于JavaScript的出色反馈,我强烈推荐使用Douglas Crockford的JSLint。它将扫描您的代码以查找常见错误,并找到清理建议。
我还建议您阅读小书 JavaScript:The Good Parts 。它包含许多编写可维护JS代码的技巧。
答案 1 :(得分:40)
JavaScript没有“块作用域”,它只有函数作用域 - 因此在if语句(或任何条件块)中声明的变量被“提升”到外部作用域。
if(true) {
var foo = "bar";
}
alert(foo); // "bar"
这实际上描绘了一幅更清晰的画面(并在采访中出现,来自经验:)
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
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
函数的内部范围可以访问包含它的环境,但不能反过来。
为了回答你的第二个问题,可以通过最初构建一个满足所有条件的“最小”对象,然后根据已经满足的特定条件对其进行扩充或修改来实现优化。
答案 2 :(得分:3)
答案 3 :(得分:2)
只要它们位于同一个函数中,if语句中声明的变量将可用于outisde。
在您的情况下,最好的方法是声明结构,然后在两种情况下修改对象的不同部分:
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" : ""
}]
}
if(state != "ed") {
// modify appropriate attrs of structure (e.g. set title and class to cancel)
}
答案 4 :(得分:2)
是在“if”语句中声明和分配的变量,仅可见 在“if”块内或整个函数内?
在Javascript中,所有变量都是
我在以下代码中执行此操作吗? (似乎有用,但是 多次声明“var结构”似乎很尴尬)任何清洁工 溶液
是。更清晰的解决方案可能是构建structure
的基类,并在每种情况下修改不同的内容。