Nest class'对象中的方法,但保留实例范围

时间:2017-05-09 20:57:25

标签: javascript coffeescript ecmascript-6

我意识到我不知道如何做一些我认为非常重要的事情,即创建一个子类',或者换句话说,一个嵌套对象在一个具有以下功能的实例上参考实例。

例如,我希望能够这样做:

sequence = new Sequencer(2, [true, true])
sequence.is_valid # returns true or false

使用以下代码:

class Sequencer

  Validations:

    correct_sequence_length: ->
      @division == @sequence.length

    positive_length: ->
      @division > 0

  constructor: (args) ->
    { @sequence, @division } = args

  is_valid: ->
    @Validations.correct_sequence_length() &&\
    @Validations.positive_length()

然而,似乎由于Validations是一个对象,它有自己的范围,其方法中的this并不引用该实例,而是Validations宾语。这意味着它无法访问@sequence@tempo。我也试过使用箭头功能,但它没有用。

处理此问题的最佳方法是使Validations成为自己的类吗?

1 个答案:

答案 0 :(得分:0)

是的,您需要一个额外的类,其中包含对Sequencer的引用:

class Sequencer

  @Validations: class
    constructor: (@target) ->

    correct_sequence_length: ->
      @target.division == @target.sequence.length

    positive_length: ->
      @target.division > 0

  constructor: ({ @sequence, @division }) ->
    @validations = new Sequencer.Validations(@)

  is_valid: ->
    @validations.correct_sequence_length() &&
    @validations.positive_length()

(为方便起见,我将其嵌套为Sequencer的静态属性,但不需要这样做。)

如果您没有将validations作为对象,则箭头功能会起作用:

class Sequencer

  constructor: ({ @sequence, @division }) ->

  validations: ->
#             ^^^^
    correct_sequence_length: =>
      @division == @sequence.length

    positive_length: =>
      @division > 0

  is_valid: ->
    v = @validations()
    v.correct_sequence_length() && v.positive_length()

您也可以使用构造函数中的箭头函数创建该对象:

class Sequencer

  constructor: ({ @sequence, @division }) ->
    @validations =
      correct_sequence_length: =>
        @division == @sequence.length
      positive_length: =>
        @division > 0

  is_valid: ->
    @validations.correct_sequence_length() &&
    @validations.positive_length()