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
725 views
in Technique[技术] by (71.8m points)

ecmascript 6 - ES6 getter/setter with arrow function

I'm using babel6 and for my pet project I'm creating a wrapper for XMLHttpRequest, for the methods I can use:

open = (method, url, something) => {
  return this.xhr.open(method, url, something);
}

but for the properties arrow function doesn't work

this works:

get status() { return this.xhr.status; }

but I can not use

get status = () => this.xhr.status;

Is this intentional?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

According to the ES2015 grammar, a property on an object literal can only be one of four things:

PropertyDefinition:

  • IdentifierReference
  • PropertyName : AssignmentExpression
  • MethodDefinition

The only one of these type that allows a leading get is MethodDefinition:

MethodDefinition :

  • PropertyName ( StrictFormalParameters ) { FunctionBody }
  • GeneratorMethod
  • get PropertyName ( ) { FunctionBody }
  • set PropertyName ( PropertySetParameterList ) { FunctionBody }

As you can see, the get form follows a very limited grammar that must be of the form

get NAME () { BODY }

The grammar does not allow functions of the form get NAME = ....


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

...