简体   繁体   English

我可以在javascript中使用花括号来分隔代码段吗

[英]Can I use curly braces in javascript to separate sections of code

Here is some sample code.这是一些示例代码。 I'd like to know if there is any reason why I shouldn't do this.我想知道是否有任何理由为什么我不应该这样做。

//some code
var x = "hello";

{
    var y = "nice";

    function myfunction() {
        //do stuff . . .
    }
}

The benefit of doing this I see is being able to organize sections of code in chunks and have auto formatters do some work with that...我认为这样做的好处是能够以块的形式组织代码部分,并让自动格式化程序对此进行一些工作......

In my tests {} does not affect the scope when creating a var or function.在我的测试中,{} 在创建 var 或函数时不会影响范围。

This answer was written in times of earlier JavaScript implementations.这个答案是在早期 JavaScript 实现的时候写的。 While the same rules for var apply, ECMAScript 2015 (aka ES6) introduce the let variable declaration statement, which follows "traditional" block-scoped rules .虽然适用于var的相同规则,但ECMAScript 2015(又名 ES6)引入了let变量声明语句,它遵循“传统”块范围规则

Example of let scoping with a Block, which logs "1", "2", "1":使用块的let范围的示例,记录“1”、“2”、“1”:

{ let x = 1; console.log(x); { let x = 2; console.log(x) }; console.log(x) }

The MDN Reference on Block summarizes the usage of blocks as: MDN Reference on Block总结了的用法:

Important: JavaScript does not have block scope.重要提示:JavaScript没有块范围。 Variables introduced with a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself.块中引入的变量的作用域是包含函数或脚本,并且设置它们的效果在块本身之外持续存在。 In other words, block statements do not introduce a scope.换句话说,块语句不引入作用域。 Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java.尽管“独立”块是有效的语法,但您不想在 JavaScript 中使用独立块,因为如果您认为它们在 C 或 Java 中执行此类块,那么它们不会执行您认为它们所做的事情。


As discussed on MDN, the syntax is perfectly valid as { StatementList } (aka Block ) is a valid Statement production..正如在 MDN 上讨论的那样,语法是完全有效的,因为{ StatementList } (又名Block )是一个有效的Statement产生式..

However;然而; and because this is very important: a new block does not introduce a new scope .因为这是非常重要的:一个新的块引入新的范围 Only function bodies introduce new scopes.只有函数体引入了新的作用域。 In this case, both the x and y variables have the same scope.在这种情况下,无论xy变量具有相同的范围。

In addition a FunctionDeclaration should appear only as a top-level statement - that is, it must be a statement directly under a Program or Function body, not a Block.此外, FunctionDeclaration 应该作为顶级语句出现——也就是说,它必须是直接在程序或函数体下的语句,而不是块。 In this case the declaration of myfunction is "not reliably portable among implementations" .在这种情况下, myfunction的声明“不能在实现之间可靠地移植”

There is the IIFE (Immediately Invoked Function Expression) pattern which can be used and, while it addresses the technical issues above, I would not recommend it here as it complicates the code.有可以使用的IIFE(立即调用函数表达式)模式,虽然它解决了上述技术问题,但我不会在这里推荐它,因为它会使代码复杂化。 Instead, I would simply create more named functions (named functions can be nested!), perhaps in different modules or objects, as appropriate.相反,会简单地创建更多命名函数(命名函数可以嵌套!),可能在不同的模块或对象中,视情况而定。

var x = "hello";

;(function () {
   // New function, new scope
   // "y" is created in scope, "x" is accessible through the scope chain
   var y = "nice";

   // Now VALID because FunctionDeclaration is top-level of Function
   function myfunction() {
   }
})(); // Invoke immediately

// No "y" here - not in scope anymore

Realize this is old, but figured I would update for ES2015.意识到这是旧的,但我想我会更新 ES2015。

The do have a bit more meaning with let + const as found here https://babeljs.io/docs/learn-es2015/使用 let + const 确实有更多含义,如在此处找到的https://babeljs.io/docs/learn-es2015/

 function f() { { let x; { // okay, block scoped name const x = "sneaky"; // error, const x = "foo"; } // okay, declared with `let` x = "bar"; // error, already declared in block let x = "inner"; } }

I don't understand the reasoning behind the outermost curly braces, but functions are always written inside curly braces in javascript.我不明白最外面的大括号背后的原因,但函数总是写在 javascript 的大括号内。

If you are working with other developers they may find the outer curly braces more confusing than helpful and there could be some negative effects : https://web.archive.org/web/20160131174505/http://encosia.com/in-javascript-curly-brace-placement-matters-an-example/如果您正在与其他开发人员合作,他们可能会发现外花括号更令人困惑而不是有用,并且可能会产生一些负面影响: https : //web.archive.org/web/20160131174505/http : //encosia.com/in- javascript-curly-brace-placement-matters-an-example/

There are probably many reasons NOT to write code this way... readability is #1, as most would find this makes the code harder to read.不以这种方式编写代码的原因可能有很多……可读性是#1,因为大多数人会发现这会使代码更难阅读。 However, there is technically nothing wrong with coding like this, and if it's easier for you to read, then it should be fine.但是,像这样的编码在技术上没有任何问题,如果您更容易阅读,那么应该没问题。

I think there will be problems with this convention when you start coding more complex programs.我认为当你开始编写更复杂的程序时,这个约定会有问题。 There must be a good reason why people don't code like that other than adding extra lines of code.除了添加额外的代码行之外,人们不这样编码肯定有很好的理由。

But since Javascript doesn't have block scoping, the code will still work.但是由于 Javascript 没有块作用域,代码仍然可以工作。

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

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