Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
200 views
in Technique[技术] by (71.8m points)

javascript - why obj={x,y} works in Chrome?

var obj = { type: 'data', x, y, data: []}

Obviously this was my typo, {x,y} should have been {x:x, y:y}. But it does what I want, in Chrome, field x gets the value of a local variable x.

But why does it work?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It is part of the ECMAScript 2015 (or ECMAScript 6). You can create new properties in Objects in Object literals, just by specifying the identifiers.

Quoting MDN's Object Initializer's Property Definitions section,

With ECMAScript 6, there is a shorter notation available to achieve the same:

var a = "foo", 
    b = 42, 
    c = {};

// Shorthand property names (ES6)
var o = { a, b, c };

The corresponding section in ECMAScript 6 specification is here,

AssignmentProperty : IdentifierReference Initializeropt

  1. Let P be StringValue of IdentifierReference.
  2. Let lref be ResolveBinding(P).
  3. ReturnIfAbrupt(P).
  4. Let v be GetV(value, P).
  5. ReturnIfAbrupt(v).
  6. If Initializeropt is present and v is undefined, then
    1. Let defaultValue be the result of evaluating Initializer.
    2. Let v be GetValue(defaultValue).
    3. ReturnIfAbrupt(v).
    4. If IsAnonymousFunctionDefinition(Initializer) is true, then
      1. Let hasNameProperty be HasOwnProperty(v, "name").
      2. ReturnIfAbrupt(hasNameProperty).
      3. If hasNameProperty is false, perform SetFunctionName(v, P).
  7. Return PutValue(lref,v).

Basically, the specification says that, if you are using just an identifier, a new property with the name of the identifier will be created, and the value will be the actual value of that identifier. It can even be a name of the function.

var a = "foo", b = 42, c = {}, d = function () {};    
console.log({a, b, c, d});
// { a: 'foo', b: 42, c: {}, d: [Function] }

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...