1

如果我有这个模型:

var myParentModel = Backbone.Model.extend({
   defaults:{ parent1: null,
              parent2: null}
)};

我有另一个模型:

var myModel = myParentModel.extend({
   defaults: {child1: null,
              child2: null}
)};

如果我实例化一个新的 myModel:

var mymodel = new myModel({child1: 'mychild1'});

在 attributes 属性中我只设置了默认的 child2 属性,如何实现继承父模型的 parents 属性?

4

4 回答 4

3

在 github 中有一篇关于这个问题的有趣帖子,我实施的解决方案是这样的:

myModel.prototype.defaults = 
    _.extend({
        child1: null,
                child2: null
    }, myParentModel.prototype.defaults, 
       myModel.prototype.defaults);

使用下划线函数:extend,我们有了一个新的对象,默认带有父子原型,这是一个很好的多重继承解决方案

于 2012-07-01T17:54:25.833 回答
2

我使用了这个,此时如果您在同一范围内,则不需要使用原型:

var abstractDefaults = {
  parent1 : '',
  parent2 : ''
};
var MyParentModel = Backbone.Model.extend({
   defaults: abstractDefaults 
});
var MyModel = Backbone.Model.extend({
   defaults: _.extend( abstractDefaults, {
     child1 : '',
     child2 : ''
   } ) 
}); 
console.log(new MyModel().toJSON());
于 2012-07-02T22:56:04.240 回答
1

我真的建议使用函数来扩展默认属性,如下所示:

var MyParentModel = Backbone.Model.extend({
    defaults: {
        parent1 : '',
        parent2 : ''
    }
});
var MyModel = MyParentModel.extend({
    defaults: function() {
        return _.extend(
            {
                child1 : '',
                child2 : ''
            },
            MyParentModel.prototype.defaults
        );
    }
});

The reason is that you will avoid some troubles with a shared reference to the new default attributes between your different instances of the MyModel object

To make it clearer, if your default attributes contains array and if you instantiate your MyModel more than once, the attributes which contains the array will be shared between each instances. Using a function to declare your default attributes will avoid it.

I hope I'm clear enough.

于 2015-03-18T10:21:49.710 回答
1

You can also use ES6 destructuring

const MyParentModel = Backbone.Model.extend({
  defaults: {
    parent1 : '',
    parent2 : ''
  }
});

const MyModel = MyParentModel.extend({
  defaults: {
    child1: '',
    child2: '',
    ...MyParentModel.prototype.defaults
  }
});
于 2018-06-05T12:40:26.820 回答