IF语句中的javascript变量范围 [英] javascript variable scope in the IF statement

查看:222
本文介绍了IF语句中的javascript变量范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在if语句中声明和赋值的变量是仅在if块中还是在整个函数内可见?

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

我是否在以下代码中执行此操作? (似乎工作,但多次声明var结构似乎很尴尬)任何更清洁的解决方案?

Am I doing this right in the following code? (seems to work, but declaring "var structure" multiple times seems awkward) any cleaner solutions?

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


推荐答案

1)对于整个功能范围,可见变量。因此,您只应声明一次。

1) Variables are visible for the whole function scope. Therefore, you should only declare them once.

2)您不应在示例中将变量声明两次。我建议在函数顶部声明变量,然后稍后设置值:

2) You should not declare the variable twice in your example. I'd recommend declaring the variable at the top of the function, then just setting the value later:

function actionPane(state) {
    var structure;
    if(state === "ed") {
        structure = {    
            ...

关于JavaScript的优秀反馈,我强烈建议使用Douglas Crockford的 JSLint 。它将扫描您的代码以查找常见错误,并找到清理建议。

For excellent feedback on JavaScript, I highly recommend using JSLint by Douglas Crockford. It will scan your code for common errors, and find suggestions for cleanup.

我还建议您阅读小书 JavaScript:The Good Parts 。它包含许多编写可维护JS代码的技巧。

I also recommend reading the small book JavaScript: The Good Parts. It contains a lot of tips for writing maintainable JS code.

这篇关于IF语句中的javascript变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆