javascript variable scope in the IF statement

后端 未结 5 1962
粉色の甜心
粉色の甜心 2020-11-30 23:53

Are variables declared and assigned in an \"if\" statement visible only within that \"if\" block or within the whole function?

Am I doing this right in the followin

5条回答
  •  猫巷女王i
    2020-12-01 00:41

    Variables declared inside the if statement will be available outisde as long as they reside in the same function.

    In your case, the best way would be to declare structure and then modify the parts of the object that differ in either case:

    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)
    }
    

提交回复
热议问题