Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript SyntaxError: invalid property id

Tags:

javascript

I am trying to execute the following JS code;

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

But I am getting an error SyntaxError: invalid property id

What is wrong with the above code?

like image 261
copenndthagen Avatar asked Jul 26 '13 10:07

copenndthagen


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 wanted an immediately-invoked function, you'll have to make that function parse 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'
};
like image 166
James Allardice Avatar answered Sep 28 '22 16:09

James Allardice


wrap with ():

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

Or:

(function test(){
  alert("123");
})();
like image 40
karaxuna Avatar answered Sep 28 '22 15:09

karaxuna