问题
I have a class that defines some defaults, and a subclass that defines some defaults. But when I create an instance of the subclass it only looks at the local defaults and does not merge its defaults with those of the parent. Is there any simple way to do this without explicitly merging the local defaults with the parent defaults in the initialize
function of every subclass?
var Inventory = Backbone.Model.extend({
defaults: {
cat: 3,
dog: 5
}
});
var ExtendedInventory = Inventory.extend({
defaults: {
rabbit: 25
}
});
var ei = new ExtendedInventory({});
console.log(ei.attributes);
This outputs:
{rabbit: 25}
Not what I want:
{cat: 3, dog: 5, rabbit: 25}
回答1:
You can't do it like that. You will have to do it after the subclass
_.extend(ExtendedInventory.prototype.defaults, {rabbit: 25});
Put this after your model definition.
来源:https://stackoverflow.com/questions/6505873/in-backbone-js-how-can-i-get-model-superclass-defaults-to-act-as-defaults-for-su