Reputation: 2977
I'm searching for a good ECMAScript 6 equivalent of the following Backbone code:
var MyModel = Backbone.Model.extend({});
var MyCollection = Backbone.Collection.extend({
model: MyModel
});
This pattern is widely used in Backbone models, views and collections. Can I do better than the code below (e.g. by creating a method named "model")?
export class MyModel extends Backbone.Model {}
export class MyCollection extends Backbone.Collection {
constructor() {
super({model: MyModel});
}
}
Upvotes: 4
Views: 258
Reputation: 161557
I'd use a getter:
export class MyModel extends Backbone.Model {}
export class MyCollection extends Backbone.Collection {
get model() {
return MyModel;
}
}
Upvotes: 3
Reputation: 7133
Of course, just don't use the class
keyword:
var MyModel = Backbone.Model.extend({});
var MyCollection = Backbone.Collection.extend({
model: MyModel
});
This code is actually more reusable than the ECMAScript 6 equivalent you wrote. The ECMAScript 6 is actually worse than the original one.
You have to understand that in JavaScript objects can exist without classes and that feature is extremely important.
Here is what Douglas Crockford wrote on prototypal inheritance back in 2008: http://javascript.crockford.com/prototypal.html
Upvotes: 0