window.never = functio...">

Why is the function called? JavaScript / Window

I have the following code in an HTML file:

<script type="text/javascript"> window.never = function() { console.log('this function is never called'); } (function(d, s, id){ var js, srjs = d.getElementsByTagName(s)[0]; if (d.getElementById(id)) {return;} js = d.createElement(s); js.id = id; js.src = "this.script.does.not.exist.js"; srjs.parentNode.insertBefore(js, srjs); }(document, 'script', 'streamrail-jssdk')); </script> 

See the script: http://jsfiddle.net/sebvaeja/

Looking at the console, you can see that the window.never function is actually being called ("this function is never called" is written to the console).

When debugging this using the Chrome dev tools in the call stack, I see that the closure was causing (first line: http://jsfiddle.net/sebvaeja/ ).

If I change the function never to go out of global scope:

  function never() { console.log('this function is never called'); } 

Then it is not called.

Can someone explain why the window.never function is called? What causes a call? I assume that this is due to the fact that the function is on the window object, but I see no reason for this.

+5
source share
2 answers

After the function expression, the brackets follow:

  window.never = function() { ... } (...) 

A line break after a function expression does not complete the variable operator, so for a parser, a function call:

 function() { ... }(...) 

In fact, you are using the same method here:

 (function(d, s, id){ // ... }(document, 'script', 'streamrail-jssdk')) 

This is an expression of a function followed by (...) and calls the function.

Solution: Add a semicolon after the definition, and you're good.


If I ever changed a function to disconnect from the global scope ... Then it is not called.

In this case, the definition of the function is interpreted as a function of the Declaration , and not an expression. Declaring a function is more like an instruction and therefore cannot be part of CallExpression. Therefore, the following bracket is interpreted as a grouping operator (as expected).

+13
source

Put a comma after the function declaration:

  window.never = function() { console.log('this function is never called'); }; 

This is because of (...) immediately after that it calls the function call.

  window.never = function() { console.log('this function is never called'); } ( ... ) // <-- Triggers call of `window.never` 
+5
source

Source: https://habr.com/ru/post/1232297/


All Articles