JavaScript SyntaxError: Invalid Property ID

I am trying to execute the following JS code:

var foo = {   func1:function(){ function test() { alert("123"); }();     alert("456");   }, myVar : 'local' }; 

But I get an error Syntax Error: invalid property id

What is wrong with the code above?

+4
source share
2 answers

You have a syntax error:

 var foo = { func1:function() { function test() { alert("123"); }(); // ^ You can't invoke a function declaration alert("456"); }, myVar : 'local' }; 

Assuming you need a function called immediately, you will need to execute this function as an expression instead:

 var foo = { func1:function() { (function test() { // ^ Wrapping parens cause this to be parsed as a function expression alert("123"); }()); alert("456"); }, myVar : 'local' }; 
+8
source

wrap with () :

 (function test(){ alert("123"); }()); 

Or:

 (function test(){ alert("123"); })(); 
+3
source

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


All Articles