Fundamental differences between utilizing CoffeeScript `extends` vs. Backbone.js `extend`

后端 未结 2 1680
春和景丽
春和景丽 2021-01-07 20:09

What are the fundamental differences between utilizing CoffeeScript extends vs. Backbone.js extend?

For example, how is

cla         


        
相关标签:
2条回答
  • 2021-01-07 20:42

    The two are intended to be equivalent. To quote the Backbone.js changelog:

    0.3.0: Backbone classes may now be seamlessly inherited by CoffeeScript classes.

    Both CoffeeScript's Child extends Parent and Backbone's Child = Parent.extend() do three important things:

    1. (Most important) They set Child.prototype to new ctor, where ctor is a function whose prototype is Parent.prototype. That establishes prototypal inheritance.
    2. They copy all of Parent's static properties onto Child.
    3. They set Child.__super__ = Parent. This is mainly to support CoffeeScript's Ruby-like super keyword in Child's methods.
    0 讨论(0)
  • 2021-01-07 20:44

    There are some differences. If you use Backbone's extend() method, you lose out on CoffeeScript's class syntactical sugar like super and static properties/methods.

    Model = Backbone.Model.extend
      set: (attrs, options) ->
        super
    

    which compiles to (incorrect)...

    var Model;
    Model = Backbone.Model.extend({
      set: function(attrs, options) {
        return set.__super__.constructor.call(this, arguments);
      }
    });
    

    You can use super this way though:

    Model = Bakbone.Model.extend()
    Model::set = ->
      super
    

    which compiles to (correct)...

    var Model;
    Model = Backbone.Model.extend();
    
    Model.prototype.set = function() {
      return Model.__super__.set.apply(this, arguments);
    };
    

    The drawback to coffeescript classes, depending on how you organize and compile your code, each class could have CoffeeScript's __extends() function appended to the top of the class definition in the compiled javascript. This extra bit of code duplicated dozens of times can considerably balloon your files. Especially true if using a framework that wraps your code in common.js modules.

    So I would use Backbone's extend() by default for lean compiled code. Then when you have a special case that would be nice to use coffeescript class syntax, then go ahead and use it... sparingly.

    0 讨论(0)
提交回复
热议问题