Skip to content

Commit

Permalink
avoid Object.prototype inheritance for col._byId
Browse files Browse the repository at this point in the history
fixes issue jashkenas#4224
  • Loading branch information
Willem Garnier committed Oct 9, 2019
1 parent 75e6d0c commit 90a41df
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 1 deletion.
2 changes: 1 addition & 1 deletion backbone.js
Original file line number Diff line number Diff line change
Expand Up @@ -1122,7 +1122,7 @@
_reset: function() {
this.length = 0;
this.models = [];
this._byId = {};
this._byId = Object.create(null);
},

// Prepare a hash of attributes (or other model) to be added to this
Expand Down
20 changes: 20 additions & 0 deletions test/collection.js
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,26 @@
assert.equal(collection2.get(model.clone()), collection2.first());
});

QUnit.test('#4224 - internal map this._byId does not inherit from Object.prototype', function(assert) {
assert.expect(4);

var col1 = new Backbone.Collection();
assert.equal(col1._byId.constructor, undefined, 'this._byId has a constructor');
assert.equal(col1._byId.hasOwnProperty, undefined, 'object prototype methods are present on this._byId');

var model = new Backbone.Model({id: 'hasOwnProperty'});
// will throw if regression
col1.set([model]);
assert.deepEqual(col1.models, [model], 'models not correctly added');

var KeyedModel = Backbone.Model.extend({idAttribute: 'key'});
var KeyedCollection = Backbone.Collection.extend({model: KeyedModel});
var col2 = new KeyedCollection();
// will throw if regression
col2.add({key: 'hasOwnProperty'});
assert.deepEqual(col2.models[0].attributes, {key: 'hasOwnProperty'}, 'models not correctly added');
});

QUnit.test('has', function(assert) {
assert.expect(15);
assert.ok(col.has(a));
Expand Down

0 comments on commit 90a41df

Please sign in to comment.