What does the colon mean in this JavaScript snippet (not an object literal)?

£可爱£侵袭症+ 提交于 2019-12-31 04:13:08

问题


I apologize for posting a duplicate-looking question, (I know, that there is a bunch of similar titled questions here), but none of the questions already present seems to suit my case.

In short, what does the colon do here:

<script>
  'use strict';
  foo: 1;

  //whatever else
</script>

I supposed this to be a syntax error, but it's not. And it's not a label, I think, since adding a line break foo; throws Uncaught SyntaxError: Undefined label 'foo' (though a doc page suggests exactly this, that it's a label).

I suppose this is some recent addition to the JavaScript syntax, since I have never heard of such use of the colon.


If anyone wonders, why I'm asking this, this is my explanation: I was reading an MDN doc page and there is an example:

var func = () => { foo: 1 };               
// Calling func() returns undefined!

It shows, that the curly braces in this case are treated as block delimiters and not an object literal. So I supposed, that somehow foo: 1 on its own must be syntactically legal. And indeed it is.

There is a question, which is supposed to cover every use of the colon in JavaScript, but it doesn't mention this, and no answer there does this either.


回答1:


If you'd have read further down the page you linked, you would see why it was written like that.

var func = () => { foo: 1 };

This is an attempt to return an object from a arrow function.

That doesn't work for reasons explained here:

This is because the code inside braces ({}) is parsed as a sequence of statements (i.e. foo is treated like a label, not a key in an object literal). (source)

So the returned value needs to be wrapped in parentheses:

var func = () => ({foo: 1});

To actually answer your question:

It's a label.

You can't just take the foo: 1 out of context like that.



来源:https://stackoverflow.com/questions/46560668/what-does-the-colon-mean-in-this-javascript-snippet-not-an-object-literal

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!