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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17878961/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 09:57:28  来源:igfitidea点击:

JavaScript SyntaxError: invalid property id

javascript

提问by testndtv

I am trying to execute the following JS code;

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

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

But I am getting an error SyntaxError: invalid property id

但我收到一个错误 SyntaxError: invalid property id

What is wrong with the above code?

上面的代码有什么问题?

回答by James Allardice

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'
};

回答by karaxuna

wrap with ():

包裹()

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

Or:

或者:

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