我目前正在研究咖啡脚本,因为它的语法比纯 JavaScript 更容易编写/理解。但是我发现使用主干和咖啡脚本的教程显示创建模型的方法如下:
class User extends Backbone.Model
  initialize: ->
    alert 'start'
这看起来很不错,但是当使用extends它时编译相当奇怪......我知道这是咖啡脚本使类在 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);
但如果你使用:
User = Backbone.Model.extend
    initialize: ->
        alert 'start'
编译得更好(更像是我写它的方式):
(function() {
  var User;
  User = Backbone.Model.extend({
    initialize: function() {
      return alert('start');
    }
  });
}).call(this);
谁能向我解释创建模型类的方式的差异,以及为什么第一种方法在教程中更频繁地使用,而第二种方法的编译更像我在纯 JavaScript 中创建模型的方式?