简体   繁体   English

大括号内的JS变量定义

[英]JS variables definition inside curly braces

I was taking a look to an old javascript file and I noticed a function like this: 我正在查看一个旧的javascript文件,并注意到这样的功能:

function mainFunction() {

  var foo = new objFoo();

  foo.name = "fooname";
  foo.desc = "foodesc";

  // some instructions here

  {

    var bar = new objBar();

    bar.name = foo.name;
    bar.desc = foo.desc;

    // some other instructions here

  }

  return(foo);

}

My question is: what is the purpose (if there is one) of those curly braces surrounding the bar object definition? 我的问题是:围绕bar对象定义的那些花括号的目的(如果有)是什么?

Thanks 谢谢

Curly braces like that in JavaScript define a block . 像JavaScript中那样的大括号定义了一个 They can be used to contain scope if a variable is initialised using either let or const , but since the variable in your example is initialised using var , they don't actually do anything (unless there's a statement in the preceding line like an if or while etc.). 如果使用letconst初始化变量,则它们用于包含范围,但是由于示例中的变量使用var初始化,因此它们实际上不做任何事情(除非在前一行中有一个ifif语句) while等)。

Just going by the code you've given us, I think it's a mis-interpretation of code or a mis-understanding of JavaScript by the developer. 仅仅按照您提供给我们的代码来看,我认为这是对代码的误解或对开发人员的JavaScript的误解。 To contain scope in JavaScript using var variables, you'll need to write closure like this: 要使用var变量在JavaScript中包含作用域,您需要像这样编写闭包:

function mainFunction() {

  var foo = new objFoo();

  foo.name = "fooname";
  foo.desc = "foodesc";

  // some instructions here

  (function () {

    var bar = new objBar();

    bar.name = foo.name;
    bar.desc = foo.desc;

    // some other instructions here

  }());

  return(foo);

}

The curly braces define a block with a local scope. 花括号定义了一个具有局部范围的块。 You may define variables using const or let in the block the scopes of which are limited to the block. 您可以使用定义变量constlet在块中的范围仅限于该块。

For example: 例如:

 const a = "world" { const a = "hello" console.log(a) } console.log(a) 

Using var inside the block of curly braces is dangerous since it overwrites variables with the same name that are defined outside the block. 在大括号块内使用var是危险的,因为它会覆盖在块外定义的具有相同名称的变量。 If you use var declarations instead of const / let , the only advantage of a block can be a better legibility. 如果使用var声明而不是const / let ,则块的唯一优点是可以提高可读性。

 var a = "world" { var a = "hello" console.log(a) } console.log(a) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM