简体   繁体   中英

Function invocation inside curly braces {}

I am trying to implement an online chat using one of the main providers. They advised me to embed a code looking like this:

<script type="text/javascript">
  function embedScriptInsideHTMLtags() {
    // responsible code
  }
  {
    embedScriptInsideHTMLtags();
  }
</script>

My question is, what is the difference between the above and the below:

<script type="text/javascript">
  function embedScriptInsideHTMLtags() {
    // responsible code
  }  
  embedScriptInsideHTMLtags();
</script>

The first example is using what's called a block statement . In this case there is no difference in the two examples. Per the MDN link:

Variables declared with var or created by function declarations in non-strict mode do not have block scope. Variables introduced within 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.

But in strict mode

identifiers declared with let and const do have block scope

and

In strict mode, starting with ES2015, functions inside blocks are scoped to that block. Prior to ES2015, block-level functions were forbidden in strict mode.

You have to understand the difference between accessing a var outside block and accessing let and const outside block one is possible(var) other is not.

Your code does not have any difference but

<script>
  function embedScriptInsideHTMLtags() {
    // responsible code
    return 'something';
  }
  {
    const b=embedScriptInsideHTMLtags();
  }
  const c= embedScriptInsideHTMLtags();
</script>

Here you can access c from the outside or other scripts but b won't be accessible. In your case if you are just calling a function then it doesn't make any difference.

Others have already answered your specific question, but I also wanted to point out that the W3C now recommends you omit the type attribute from JS <script> tags, and has since the HTML5 specification came out years ago. The specification encourages developers to not use a redundant MIME type in tags, as text/javascript is. When you use a script tag that will contain JavaScript code, you can merely write <script> without any attributes. You can read about it from the MDN documentation for the script tag

Similarly, when using the <link> tag for a stylesheet (with rel="stylesheet , you no longer need to use type="text/css" . Since CSS is the only type of stylesheet available on the web, the type attribute for stylesheets is now redundant. You can read more about that from the MDN documentation for the link tag .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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