JavaScript变量在if语句的主体中声明,它们的作用域是否局限于该主体?

10 浏览
0 Comments

JavaScript变量在if语句的主体中声明,它们的作用域是否局限于该主体?

在“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