从默认值访问静态属性

时间:2012-10-22 13:46:12

标签: javascript backbone.js

我有以下型号:

    var User = Backbone.Model.extend({
            defaults: {
                status:     this.constructor.status.OFFLINE,
            },
        },
        {
            status:   {
                OFFLINE: 0,
                ONLINE:  1,
                BUSY:    2,
                AWAY:    3,
            },
        }
    );

我也尝试过:

status:     User.status.OFFLINE

但我一直收到这个错误:

TypeError: 'undefined' is not an object (evaluating 'this.constructor.status.OFFLINE')

或者这个:

TypeError: 'undefined' is not an object (evaluating 'User.status')

有任何帮助吗?感谢

1 个答案:

答案 0 :(得分:3)

您正在尝试引用在创建用户模型时未定义的静态属性。

将默认值定义为函数

var User = Backbone.Model.extend({
    defaults: function() {
        return {status: User.status.OFFLINE}
    }
}, {
    status:   {
        OFFLINE: 0,
        ONLINE:  1,
        BUSY:    2,
        AWAY:    3
    }
});

http://jsfiddle.net/nikoshr/6XuC8/

或首先定义静态属性,然后扩展User.prototype以添加默认值:

var User = Backbone.Model.extend({}, {
    status:   {
        OFFLINE: 0,
        ONLINE:  1,
        BUSY:    2,
        AWAY:    3
    }
});

_.extend(User.prototype, {
    defaults: {
        status: User.status.OFFLINE
    }
});

var u = new User();
console.log(u.get('status'));

http://jsfiddle.net/nikoshr/6XuC8/2/