开发者

JavaScript object literal syntax

开发者 https://www.devze.com 2023-01-19 20:10 出处:网络
If the syntax for JavaScript object literals is { label: value, label: value, ... } then why is it that I\'ve seen some people use this in their code?

If the syntax for JavaScript object literals is

{ label: value, label: value, ... }

then why is it that I've seen some people use this in their code?

{window}

What is its purpose? I've tried that and it evaluates to window as it would without the braces. It doesn't even fit in with the object literal notation. Is it 开发者_运维问答a code block?


In the answer you referenced the poster is using a block purely as a form of commenting - he's using the structure it provides to make it clear that it's a separate block of work, but it has no intrinsic value to the code.

Clearly it's use as pseudo-comment is debatable if it confused you. I would tend to avoid it in favour of actual comments.


That's not the object literal notation. Those are braces which are coincidentally also used to represent a block.

Think,

for(var i = 0; i < 10; i++) 
{

}

See section 12.1 of the ECMAScript spec that explains the grammar and semantics of how a block works.


This question is super old, but popped up for me in some search results. This sort of syntax represents shorthand property names in ES2015. For example, if you have some local variables defined, you can quickly populate a new object:

let a = 'hello';
let b = 'world';
let c = { a, b };  // equivalent to { a: 'hello', b: 'world' }

So the original example of {window} would return a new object that looked like { window: Window } with a reference to the global window object.

0

精彩评论

暂无评论...
验证码 换一张
取 消