最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Backbone.js: Model inheritance causes shared data - Stack Overflow

programmeradmin0浏览0评论

I've been banging my head on this one for the last two days. For some reason backbone is sharing parent instance data across inherited child models. Heres an example:

var Base = Backbone.Model.extend({

  index : []

});

var Group = Base.extend({

  initialize : function() {
    this.index.push('from group');
  }

});


var User = Base.extend({

  initialize : function() {
    this.index.push('from user');
  }

});


var user = new User();
console.log(user.index); // ['from user']


var group = new Group();
console.log(group.index) // ['from user', 'from group']

What I'm looking for is:

console.log(user.index); // ['from user']
console.log(group.index) // ['from group']

Any insights?

Thanks! Matt

I've been banging my head on this one for the last two days. For some reason backbone is sharing parent instance data across inherited child models. Heres an example:

var Base = Backbone.Model.extend({

  index : []

});

var Group = Base.extend({

  initialize : function() {
    this.index.push('from group');
  }

});


var User = Base.extend({

  initialize : function() {
    this.index.push('from user');
  }

});


var user = new User();
console.log(user.index); // ['from user']


var group = new Group();
console.log(group.index) // ['from user', 'from group']

What I'm looking for is:

console.log(user.index); // ['from user']
console.log(group.index) // ['from group']

Any insights?

Thanks! Matt

Share Improve this question asked Apr 23, 2012 at 0:43 MattMatt 22.9k25 gold badges85 silver badges118 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 14

What you are experiencing is essentially a byproduct of the way JS passes objects (or arrays) by reference and not by value. If you want index to be different for User and Group, simply instantiate it as an array in your initialize function.

var Base = Backbone.Model.extend({

initialize: function() {
  this.index = [];
}


});

The index member is like a class variable in that it's in the prototype chain of Base and thus shared by all instances just as the methods it contains are also shared. Try switching the order of the instantiating User and Group. Now what does index contain? It's reverse right? That's because they are sharing everything the object passed to extend.

In order for it to be an instance variable you'll need to instantiate it in a constructor for Base, and have each subclass call that constructor from their respective constructors. Like:

var Base = Backbone.Model.extend({
    initialize: function() {
       this.index = [];
    }
});

var User = Base.extend({
    initialize: function() {
        Base.prototype.initialize.call( this );
        this.index.push('User');
    }
});

// repeat it for group.
发布评论

评论列表(0)

  1. 暂无评论