Ethic
Ethic

Reputation: 45

I have an anonymous function without parentheses, how does this work?

New to javascript,but i know that form

<script>(function(){ somecode })();</script> 

will immediately run somecode when it be interpreted.But when i was reading a html5 game source code,I encountered some code which form like this:

<script>(function(){})</script>

There is no parentheses attached.So what does it mean?

source code:https://github.com/oxyflour/STGame and the index.html has code form like below:

<script>(function(){})</script>

Upvotes: 3

Views: 92

Answers (3)

shrys
shrys

Reputation: 5940

Refer the game.js file, they are using it as nodes that don't do anything(@Shilly) and accessing them with id in the script tag. I don't know what is being done with the d object but certainly it is being called somewhere, look how they're using the innerHTML

else if (v.tagName == 'SCRIPT' && $attr(v, 'type') == 'text/html') {
  d[v.id] = v.innerHTML;
} else if (v.tagName == 'SCRIPT') {
  d[v.id] = eval(v.innerHTML)(_t);
}

An example of what's being done:

eval(document.getElementById('myscript').innerHTML)('test');
<script id="myscript">
(function(a) {
  a ? console.log(a) : console.log('some string')
})
</script>

Upvotes: 4

Luuuud
Luuuud

Reputation: 4439

In the game.js source I found this piece of code after a quick scan:

// ... line 702
else if (v.tagName == 'SCRIPT') {
  d[v.id] = eval(v.innerHTML)(_t);
}
// ...

So it's getting the innerHTML of the <script/> tag and executing it via eval().

Upvotes: 1

Angelos Chalaris
Angelos Chalaris

Reputation: 6747

As far as I can tell, this does nothing. It only evaluates and returns, so no call or anything.

The (function(){})() is called an IIFE - Immediately Invoked Function Expression). This, however, is an IIFE without the last parentheses (() at the end), which means it will not be called right after its definition.

Therefore, the purpose of this code might be either to keep for later use or maybe the person writing it forgot to call it or something similar. It's not a pattern that is actually used anywhere that I have seen.

Upvotes: 0

Related Questions