if 语句主体中声明的 JavaScript 变量的作用域是否仅限于主体?

发布于 2024-11-28 05:29:33 字数 1526 浏览 1 评论 0原文

在“if”语句中声明和分配的变量是否仅在该“if”块或整个函数内可见?

我在下面的代码中这样做正确吗? (似乎有效,但多次声明“var 结构”似乎很尴尬)有更干净的解决方案吗?

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

意中人 2024-12-05 05:29:33

1) 变量在整个函数范围内可见。因此,您应该只声​​明一次。

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

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

为了获得有关 JavaScript 的出色反馈,我强烈建议使用 JSLint,作者:Douglas Crockford。它将扫描您的代码以查找常见错误,并找到清理建议。

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

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

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 = {    
            ...

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.

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

握住你手 2024-12-05 05:29:33

注意:此答案来自 2011 年。不可能使用 letconst 声明变量,并使其作用域保持在条件 if 内堵塞。


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

函数的内部作用域可以访问它所在的环境,但反之则不行。

为了回答你的第二个问题,可以通过最初构造一个满足所有条件的“最小”对象,然后根据已满足的特定条件来增强或修改它来实现优化。

NOTE: This answer is from 2011. It's not possible to declare a variable with either let or const and have its scope remain within a conditional if block.


JavaScript has no "block scope", it only has function scope - so variables declared inside an if statement (or any conditional block) are "hoisted" to the outer scope.

if(true) {
    var foo = "bar";
}
alert(foo); // "bar"

This actually paints a clearer picture (and comes up in interviews, from experience :)

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

Function scope, in JavaScript, typically refers to closures.

var bar = "heheheh";
var blah = (function() {
    var foo = "hello";
    alert(bar); // "heheheh"
    alert(foo); // "hello" (obviously)
});

blah(); // "heheheh", "hello"
alert(foo); // undefined, no alert

The inner scope of the function has access to the environment in which it is contained, but not the other way around.

To answer your second question, optimisation can be achieved by initially constructing a 'minimal' object which satisfies all conditions and then augmenting or modifying it based on particular condition(s) which has/have been satisfied.

故事与诗 2024-12-05 05:29:33

ECMAScript 2015 (ES6) 包含两个新关键字,最终允许 JavaScript 完成正确的块作用域,而无需使用变通方法、通俗语法:

  1. let
  2. const

ECMAScript 2015 (ES6) includes two new keywords that finally allow JavaScript to accomplish proper block scoping without the need to use work-around, colloquial syntax:

  1. let
  2. const
贱人配狗天长地久 2024-12-05 05:29:33

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

在 Javascript 中,所有变量都是

  • 全局作用域
  • 局部作用域(整个函数) - Javascript 没有“块作用域”,其中变量仅在局部作用域(函数)的较小块中可用

我在下面的代码中做得对吗? (似乎有效,但是
多次声明“var 结构”似乎很尴尬)任何清洁工
解决方案?

是的。更简洁的解决方案可能是构建结构的基类,并修改每种情况下的不同之处。

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

In Javascript, all variables are either

  • global scope
  • local scope (entire function) - Javascript doesn't have a "block scope" where variables are only available with a smaller block of the local scope (function)

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

Yes. A cleaner solution might be to build a base class of structure, and modify what is different in each case.

摘星┃星的人 2024-12-05 05:29:33

只要在 if 语句内声明的变量位于同一函数中,它们就可以在外部使用。

对于您的情况,最好的方法是声明结构,然后修改对象中在两种情况下不同的部分:

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

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)
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文