且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

ES6对象方法分配之间的区别:a,'a'和['a']?

更新时间:2023-11-05 23:33:16


这三种语法有区别吗?


不是在你的例子中的结果wrt。



然而,不同的语法确实有不同的特征。定义属性名称的方式不是特定于方法定义btw,规则适用于所有属性名称:




  • 属性名称

      {
    foo:...,
    10e4:...,
    如果:...,
    }


  • 还需要引用其他内容:

      {
    'foo + bar':...,
    'abc def':...,
    '123,45':...,
    }


  • ES6中的方括号语法是新的,可以动态计算属性名称:

      {
    [getPropertyName()]:...,
    ['item'+(i * 3)]:... ,
    }








为什么这些语法有效?


因为语法允许:

  MethodDefinition: 
PropertyName(StrictFormalParameters){FunctionBody}
GeneratorMethod
get PropertyName(){FunctionBody}
set PropertyName(PropertySetParameterList){FunctionBody}

PropertyName:
LiteralPropertyName
ComputedPropertyName

LiteralPropertyName:
IdentifierName
StringLiteral
NumericLiteral

ComputedPropertyName:
[AssignmentExpression ]

(不知道你期望什么样的答案)



如果您将方法等同于为属性分配函数,将属性名称的相同规则应用于函数/方法名称似乎是有意义的。


With ES6, I can create a new object with functions like the following:

var obj = {
    something() {}
};

That makes sense. But I can also do this:

var obj = {
    'something'() {}
};

Or I can do this:

var obj = {
    ['something']() {}
};

Is there a difference between these three syntaxes? Why are all of these syntactically valid?

Is there a difference between these three syntaxes?

Not wrt to the results in your example.

However, the different syntaxes do have different characteristics. The way the property name is defined is not specific to method definitions btw, the rules apply to all property names:

  • Property names that are valid identifier names or number literals don't need to be quoted:

    {
      foo: ...,
      10e4: ...,
      if: ...,
    }
    

  • Anything else needs to be quoted:

    {
      'foo+bar': ...,
      'abc def': ...,
      '123,45': ...,
    }
    

  • The square bracket syntax is new in ES6 and allows you do dynamically compute property names:

    {
       [getPropertyName()]: ...,
       ['item' + (i * 3)]: ...,
    }
    


Why are all of these syntactically valid?

Because the grammar allows it:

MethodDefinition :
    PropertyName ( StrictFormalParameters ) { FunctionBody }
    GeneratorMethod
    get PropertyName ( ) { FunctionBody }
    set PropertyName( PropertySetParameterList ) { FunctionBody }

PropertyName :
    LiteralPropertyName
    ComputedPropertyName

LiteralPropertyName :
    IdentifierName
    StringLiteral
    NumericLiteral

ComputedPropertyName :
    [ AssignmentExpression ]

(not sure what kind of answer you expect here)

If you consider methods to be equivalent to assigning a function to the property, it seems to make sense to apply the same rules for property names to function/method names.