什么是Backbone.Model.extend()与类X的区别扩展Backbone.Model?

时间:2013-06-23 10:51:26

标签: javascript backbone.js coffeescript

在JavaScript中,我将不得不使用

Backbone.Model.extend()

为我的模型创建“类”。但在CoffeeScript中我可以使用

class X extends Backbone.Model

两者之间的区别是什么?有什么理由说我应该使用一个而不是另一个?

一个简单的测试,看看差异http://jsfiddle.net/jiewmeng/t6ZPd/

Test = Backbone.Model.extend()
class Test2 extends Backbone.Model

console.log Test
/*
function (){return i.apply(this,arguments)} 
*/

console.log Test2
/*
function Test2() {
    _ref = Test2.__super__.constructor.apply(this, arguments);
    return _ref;
  } 
*/

我认为它没有显示所有代码......但extends()似乎稍微简单一些。 JUst好奇还有其他差异吗?

1 个答案:

答案 0 :(得分:2)

coffeescript在闭包顶部创建extends方法:

__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; };

下划线将其定义为:http://underscorejs.org/docs/underscore.html#section-76

实施略有不同,但效果是一样的。

如果您使用的是Backbone或更具体的Underscore,您可以选择执行任一方法,但coffeescript中的extends允许您扩展任何类,而不需要像Underscore或Backbone这样的依赖项。

在使用骨干的情况下,您可以使用该方法执行的示例可能会覆盖构造函数,以便为骨干在其选项对象中不支持的类提供可选项

class MyView extends Backbone.View
  constructor: (foo, bar, options)->
    # locals foo and bar are now assigned
    @foo = foo
    @bar = bar
    super(options) # calls to Backbone.View with the normal options

myView = new MyView("foo","bar", {model: someModel, el: $('#someEl')})
myView.foo # "foo"
myView.model == someModel # true
相关问题