为什么obj = {x,y}适用于Chrome? [英] why obj={x,y} works in Chrome?

查看:98
本文介绍了为什么obj = {x,y}适用于Chrome?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

显然这是我的错字, {x,y} 应该是{x:x,y:y}。但是,在Chrome中,您可以使用 x 获取局部变量 x 的值。

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.

但是为什么它工作?

推荐答案

它是ECMAScript 2015的一部分(或ECMAScript 6)。您可以通过指定标识符在对象文字中的对象中创建新属性。

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.

引用 MDN的Object Initializer的Property Definitions部分


使用ECMAScript 6,可以使用较短的符号来实现相同的功能:

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







ECMAScript 6规范中的部分是 here


AssignmentProperty IdentifierReference sub>


  1. P 为StringValue的 IdentifierReference / li>
  2. lref 为ResolveBinding( P

  3. ReturnIfAbrupt( / em>)

  4. v 为GetV( P )。 >
  5. ReturnIfAbrupt( v )。

  6. 如果初始化器 opt 存在而 v 未定义,然后

  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. defaultValue 成为结果评估初始化程序

  2. v 为GetValue ( defaultValue )。

  3. ReturnIfAbrupt( v

  4. 如果IsAnonymousFunctionDefinition > Initializer )是 true ,然后

  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. hasNameProperty 为HasOwnProperty

  2. 如果

  3. 返回值( hasNameProperty
  4. hasNameProperty
    false ,执行SetFunctionName( v P
  1. Let hasNameProperty be HasOwnProperty(v, "name").
  2. ReturnIfAbrupt(hasNameProperty).
  3. If hasNameProperty is false, perform SetFunctionName(v, P).

/ li>


  • 返回PutValue( lref v

  • 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] }
    

    这篇关于为什么obj = {x,y}适用于Chrome?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆