Coffeescript 和 Ecmascript 6 获取和设置关键字

Coffeescript and Ecmascript 6 get and set keywords

我 运行 遇到了 coffeescript 的问题,我希望能够使用 ecmascript get 和 set 关键字,但是语法在 coffeescript 中没有意义。

下面是原文的例子javascript

// A Tutorial class that takes a document in its constructor
Tutorial = function (id, name, capacity, owner) {
    this._id = id;
    this._name = name;
    this._capacity = capacity;
    this._owner = owner;
};

Tutorial.prototype = {
    get id() {
        // readonly
        return this._id;
    },
    get owner() {
        // readonly
        return this._owner;
    },
    get name() {
        return this._name;
    },
    set name(value) {
        this._name = value;
    },
    get capacity() {
        return this._capacity;
    },
    set capacity(value) {
        this._capacity = value;
    }
};

这是我对可能转化为什么的最佳猜测的示例:

class Question
  constructor: (id, @name, @capacity, @owner) ->
    @_id = id


Question::get id() ->
  return @_id

然而,这当然不会真正编译成任何有用的东西。

我看过几个解决方法的例子,但我想真正的问题是 Coffescript 是否直接支持这个?

我认为 Coffeescript 根本不支持 getter/setter 对象文字中的声明。已讨论多次,请参阅问题 64, 451, 322, 2878:

In summary: we explicitly ignore the existence of setters/getters because we consider them a bad part of JS

您可以获得的最佳解决方法是

Object.defineProperty Question::, "id",
  get: -> @_id
  enumerable: true
  configurable: true