替换对象属性时出现意外的异常

Unexpected beahviour when replacing object properties

本文关键字:意外 异常 对象 属性 替换      更新时间:2023-09-26

我正在使用摩卡对新编写的类运行测试,需要构建一些Event进行比较。我计划使用对象存根并将它们替换为Event类的实际实例,由于数据库连接的使用,这些实例具有异步构造函数。所以我使用递归调用来按顺序处理存根。问题是:我所有的存根对象都替换为最新的实例,我不知道为什么。请解释我错在哪里。

活动咖啡:

class Event
    start = 0
    duration = 0
    title = ""
    atype = {}
    constructor: (_start, _duration, _title, _atype, cb) ->
        start = _start
        duration = _duration
        title = _title
        evt = @
        ActivityType.find( {} =
            where: {} =
                title: _atype
        ).success( (res) ->
            atype = res
            cb? evt
        ).error( () ->
            throw new Error "unable to assign atype '#{_atype}'"
        )
# ...

Event.test.coffee:

# ...
suite "getEventAt", () ->
    events =
        FREE: {} =
            start: 0
            duration: Day.MINUTES_PER_DAY
            title: "Free time"
            type: "FREE"
        REST: {} =
            start: 10
            duration: 30
            title: "rest"
            type: "_REST"
        FITNESS: {} =
            start: 30
            duration: 30
            title: "fitness"
            type: "_FITNESS"
        WORK: {} =
            start: 20
            duration: 30
            title: "work"
            type: "_WORK"
    suiteSetup (done) ->
        buildEvent = (ki) ->
            ks = Object.keys events
            ( (k) ->
                v = events[k]
                new Event v.start, v.duration, v.title, v.type, (e) ->
                    events[k] = e
                    if k == ks[ks.length-1]
                        return done?()
                    return buildEvent(ki+1)
            )(ks[ki])
        buildEvent(0)
# ...

开始持续时间标题和atype是类变量,因此每次创建新事件时都会被覆盖

class Event
    constructor: (_start, _duration, _title, _atype, cb) ->
        @start = _start
        @duration = _duration
        @title = _title
        evt = @
        ActivityType.find( {} =
            where: {} =
                title: _atype
        ).success( (res) =>
            @atype = res
            cb? evt
        ).error( () ->
            throw new Error "unable to assign atype '#{_atype}'"
        )

请注意成功回调时的平箭头(有关更多详细信息,请参阅:http://coffeescript.org/#fat-arrow)