Backbone中未在继承模型上设置默认属性

时间:2013-08-22 08:30:13

标签: javascript inheritance backbone.js

我正在尝试在学习Backbone的同时构建一个简单的2D游戏,而我在继承如何工作方面遇到了困难。为什么不设置EntityModel中的默认值? tick()的输出始终为:

x: undefined
y: undefined

简化代码:

$(function(){

EntityModel = Backbone.Model.extend({

    defaults: function(){
        return {
            x : 0,
            y : 0
        };
    },

    tick: function(){
        console.log('x: ' + this.get('x'));
        console.log('y: ' + this.get('y'));
    }

});

PlayerModel = EntityModel.extend({

    defaults: function() {
        return {
            name : 'John Doe',
            health : 10
        };
    },

    initialize: function(options){
        console.log('New player ('+this.get('name')+') entered the game');
    }

});

var player1 = new PlayerModel();

var gameloop = window.setInterval(function(){
    player1.tick();
}, 40);

});

1 个答案:

答案 0 :(得分:2)

defaults中的PlayerModel声明掩盖了在其父类中完成的声明。您必须明确合并EntityModel中的默认值。例如:

var PlayerModel = EntityModel.extend({
    defaults: function() {
        var defaults_parent = _.result(EntityModel.prototype, 'defaults'),
            defaults_self = {
                name : 'John Doe',
                health : 10
            };

        return _.defaults(defaults_self, defaults_parent);
    }
});

演示http://jsfiddle.net/nikoshr/epCsy/