简体   繁体   English

为什么这个 HTML javascript 用花括号包裹?

[英]Why is this HTML javascript wrapped in curly braces?

I'm trying to understand this source code to learn how to make artblocks.我试图理解这个源代码来学习如何制作艺术块。

https://api.artblocks.io/generator/9000000 https://api.artblocks.io/generator/9000000

The code looks like this:代码如下所示:

<script>
  'use strict';
  {
    ....
  }
</script>

Why is the whole script in the HTML wrapped in curly braces?为什么 HTML 中的整个脚本用花括号括起来? And why does the script still work?为什么脚本仍然有效?

It's just a plain block.这只是一个普通的块。

Why is the whole script in the HTML wrapped in curly braces?为什么 HTML 中的整个脚本用花括号括起来?

Presumably to avoid creating or interfering with global variables - like an IIFE.大概是为了避免创建或干扰全局变量——比如 IIFE。 Otherwise, if the whole script was on the top level, it could cause problems with other scripts running on the same page.否则,如果整个脚本都在顶层,可能会导致在同一页面上运行的其他脚本出现问题。

For example, if there was例如,如果有

<script>
// script 1
const someElement = document.querySelector('.something');
</script>

<script>
// unrelated script 2
const someElement = document.querySelector('.somethingElse');
</script>

An error would be thrown, because both scripts are populating the top level with their variables.将引发错误,因为两个脚本都使用其变量填充顶层。 Putting standalone scripts into their own blocks significantly reduces the possibility of name collisions, hence将独立脚本放入自己的块中显着降低了名称冲突的可能性,因此

<script>
// script 1
{
  const someElement = document.querySelector('.something');
  // other code
}
</script>

That said, an IIFE is probably a better approach - it's much more common, more compatible, and doesn't have problems with function declarations .也就是说, IIFE 可能是一种更好的方法——它更常见、更兼容,并且与 function 声明没有问题

<script>
// script 1
(function() {
  const someElement = document.querySelector('.something');
  // other code
})();
</script>

In JavaScript, curly braces are used to create a new block.在 JavaScript 中,大括号用于创建新块。 Curly braces were placed to make sure no code would conflict with the code inside and vice versa, make sure the code in the curly braces didn't affect some other code.放置大括号是为了确保没有代码与内部代码冲突,反之亦然,确保大括号中的代码不会影响其他代码。

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

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