JavaScript语法错误:无效的属性id

JavaScript语法错误:无效的属性id,javascript,Javascript,我正在尝试执行以下JS代码 var foo = {   func1:function(){ function test() { alert("123"); }();     alert("456");   }, myVar : 'local' }; 但是我犯了个错误 SyntaxError:无效的属性id 上述代码有什么问题?您有语法错误: var foo = { func1:function() { function test(

我正在尝试执行以下JS代码

var foo = {
  func1:function(){
    function test()
    {
      alert("123");
    }();
    alert("456");
  },
  myVar : 'local'
};
但是我犯了个错误 SyntaxError:无效的属性id


上述代码有什么问题?

您有语法错误:

var foo = {
    func1:function() {
        function test() {
            alert("123");
        }();
//       ^ You can't invoke a function declaration
        alert("456");
    },
    myVar : 'local'
};
假设您需要一个立即调用的函数,则必须将该函数作为表达式进行解析:

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

或:

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