- Notifications
You must be signed in to change notification settings - Fork4
CS2 Discussion: Features: Getters and Setters #17
Description
ES6 getters and setters don’t have there own discussion yet, and they came up in the discussion of decorators, specifically the need the ensure that any syntax that CoffeeScript adopts for defining getters and setters must allow decorators to be applied to the function literals.
This is a general discussion, but to carry over what was brought up already: From the example@carlmathisen used when he raised the issue, we can currently do this (note thatreadonly
is a decorator):
classPersonname:readonly->return"#{@first}#{last}"
That works well, but the getter and setter syntax needs to allow decorators to be applied in a similar way (or an alternative must be provided).
EDIT by@GeoffreyBooth Consensus from the below thread:
Theget
andset
shorthand syntax is too infrequently used, and a discouraged practice, for CoffeeScript to support directly. Getters and setters can be created via theObject.defineProperty
method, so they technically alreadyare supported in CoffeeScript; supporting the shorthand syntax as well just makes them more convenient to use, but Douglas Crockford argues that we should rarely if ever be using them.
So the task for CS2 is to have the compiler throw an error when it appears that aget
orset
shorthand syntax keyword is being used. Things like the following:
classAgetb:->c=getd:->e=->getf:->
Andset
for all of the same. The aboveall compiles, which isn’t a good thing. These should throw compiler errors,without prohibiting people from using variables or functions namedget
orset
elsewhere in the code. Basically when a call to a function namedget
orset
is given an argument that is an object with one property, and that property’s value is a function, we throw an error. In other words, this:
get({b:function(){}});
If anyone needs to call a function namedget
and pass an object, well, they just need to define the object ahead of time and assign it to a variable, and then callget
likeget(obj)
. That’s a reasonable workaround for what should be a tiny edge case. What weshouldn’t do, even though we could, is makeget
andset
keywords. They’re not keywords in JavaScript, and they strike me as quite plausible names for functions, so I don’t want to cause a breaking change for people who have such variable names when we can solve this problem with more precision.