javascript - 替换对象属性时出现意外行为

标签 javascript coffeescript

我正在使用 mocha 对新编写的类运行测试,并且需要构建许多 Event 来进行比较。我计划使用对象 stub 并将其替换为 Event 类的实际实例,由于数据库连接的使用,该实例具有异步构造函数。因此,我使用递归调用来按顺序处理 stub 。 问题是:我所有的 stub 对象都替换为最新的实例,我不知道为什么。请解释我哪里错了。

事件.咖啡:

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)

关于javascript - 替换对象属性时出现意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19220450/

相关文章:

javascript - 禅编码 : ability to ascend the DOM tree using ^

javascript - 我们可以使用键控函数的对象在运行时定义类吗?

javascript - 从数组中顺序执行一堆 WinJS promise

javascript - CoffeeScript 和 JavaScript 中三元(问号运算符)之间的区别?

javascript - 添加按键事件

javascript - 选择菜单 ('refresh',正确)

javascript - 替换 Wakanda 2 中的 setLoginListener

javascript - 惯用地查找给定值在数组中出现的次数

javascript - 使用 React 发出和处理全局事件

javascript - 可以使用正则表达式来比较和匹配单词集吗?