Czy zmienne są zadeklarowane i przypisane w wyrażeniu "jeśli" widoczne tylko w tym bloku "jeśli" lub w całej funkcji?Zakres zmiennej javascript w instrukcji IF
Czy robię to dobrze w poniższym kodzie? (wydaje się działać, ale deklarowanie "struktury var" wielokrotnie wydaje się niezręczne) żadnych czystszych rozwiązań?
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;
}
Zauważ, że możesz to również zrobić: 'if (state ===" ed ") {return {...}} else {return {...}}' zamiast użycia zmiennej. –