2

在 JavaScript 中,我将不得不使用

Backbone.Model.extend()

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

class X extends Backbone.Model

2之间有什么区别。有什么理由我应该使用一个而不是另一个?

一个简单的测试看看有什么区别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()似乎稍微简单一些。只是好奇还有其他区别吗?

4

1 回答 1

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,您可以选择使用任何一种方法,但extends在 coffeescript 中允许您扩展任何类而无需像 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
于 2013-06-24T19:39:17.183 回答