-1

我是 CoffeeScript 和 Jasmine 的初学者。起初,我尝试使用以下代码通过测试:

class Counter
    count: 0

    constructor: ->
        @count = 0

    increment: ->
        @count++

    decrement: ->
        @count--

    reset: ->
        @count = 0

root = exports ? this
root.Counter = Counter

茉莉花测试代码如下:

describe("Counter", ->
    counter = new Counter
    it("shold have 0 as a count variable at first", ->
        expect(counter.count).toBe(0)
    )

    describe('increment()', ->
        it("should count up from 0 to 1", ->
            expect(counter.increment()).toBe(1)
        )
    )
)

然后好心人告诉我代码应该如下:

class Counter
    count: 0

    constructor: ->
        @count = 0

    increment: ->
        ++@count

    decrement: ->
        --@count

    reset: ->
        @count = 0

root = exports ? this
root.Counter = Counter

是的,这段代码通过了测试。但我有一个问题,前一个代码比后一个代码更自然。我不知道如何确定这个问题。谢谢您的帮助。

4

2 回答 2

2

这是前增量和后增量之间的基本区别。@count++将返回的值@count并在之后增加它。++@count将首先增加它并返回新值。这就是如果您使用@count++. 更多关于递增和递减运算符

于 2012-09-27T08:57:34.920 回答
1

如果您选择坚持发布增量,您可以将代码更改为以下内容以更清楚地了解返回值

class Counter
  count: 0

  constructor: ->
    @count = 0

  increment: ->
    @count++
    @count

  decrement: ->
    @count--
    @count
  reset: ->
    @count = 0

root = exports ? this
root.Counter = Counter

或者您可以将测试更改为:

describe('increment()', ->
  it("should count up from 0 to 1", ->
    expect(counter.count).toBe(0)
    counter.increment()
    expect(counter.count).toBe(1)
  )
)

但是你不希望增量和减量的返回值反映@count的更新值

这是一个可以使差异明显的示例: http ://coffeescript.org/#try:class%20Counter%0A%20%20count%3A%200%0A%0A%20%20increment%3A%20- %3E%0A%20%20%20%20%40count%2B%2B%0A%20%20%20%20%40count%0A%20%20%0A%20%20inc%3A%20-%3E% 0A%20%20%20%20%40count%2B%2B%0A%0A%20%20递减%3A%20-%3E%0A%20%20%20%20--%40count%0A%0A%20 %20dec%3A%20-%3E%0A%20%20%20%20%40count--%0A%0Acnt%20%3D%20new%20Counter%0Aalert%20cnt.increment()%0Aalert%20cnt.count% 0Aalert%20cnt.inc()%0Aalert%20cnt.count%0Aalert%20cnt.decrement()%0Aalert%20cnt.count%0Aalert%20cnt.dec()%0Aalert%20cnt.count

于 2012-09-27T13:24:04.253 回答