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 (eg by creating a method named "model")?
export class MyModel extends Backbone.Model {}
export class MyCollection extends Backbone.Collection {
constructor() {
super({model: MyModel});
}
}
I'd use a getter:
export class MyModel extends Backbone.Model {}
export class MyCollection extends Backbone.Collection {
get model() {
return MyModel;
}
}
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.