I am currently looking at coffee-script because the syntax is greate and easier to write/understand than pure javascript. However I found that tutorials using backbone and coffee-script show that the way to create a model is as follows:
class User extends Backbone.Model
initialize: ->
alert 'start'
This looks all nice, but when using extends it compiles rather strangely… I understand this is coffee-script’s way of making classes work in javascript.
(function() {
var User,
__hasProp = {}.hasOwnProperty,
__extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; };
User = (function(_super) {
__extends(User, _super);
function User() {
return User.__super__.constructor.apply(this, arguments);
}
User.prototype.initialize = function() {
return alert('start');
};
return User;
})(Backbone.Model);
}).call(this);
but if you use:
User = Backbone.Model.extend
initialize: ->
alert 'start'
that compiles a lot better (more like how I would write it):
(function() {
var User;
User = Backbone.Model.extend({
initialize: function() {
return alert('start');
}
});
}).call(this);
Can anyone explain to me the differences in the ways of creating a model class and why the first method is used more often in tutorials when the second one compiles more like how I would create a model in pure javascript?
These two methods are functionally equivalent, with no significant difference in how they work. There are some implementation differences, sure, but the end result is the same.
The real difference, and why you see the larger code generation from the coffeescript
extendskeyword, is that when you callBackbone.Model.extend, you are calling Backbone’s version of the same code that CoffeeScript produces. It’s encapsulated within Backbone’sextendmethod, but it’s largely similar in how it works and why.The only reason you see the CoffeeScript
extendsused everywhere, is because you’re looking at CoffeeScript examples. Honestly, that’s it. There’s no benefit to doing it one way or the other. It’s just that CoffeeScript says you should use theextendskeyword so people do it that way.