Backbone.js 你能扩展初始化的模型吗?

Backbone.js 你能扩展初始化的模型吗?,backbone.js,coffeescript,Backbone.js,Coffeescript,Entity=newthemodel(#传入属性) 然后我可以扩展实体并维护模型属性/状态吗 class TheModel extends Backbone.Model foo: #bar 编辑: class User extends Entity foo: super #more 不。让类扩展对象(而不是函数)没有意义。如果试图实例化用户类,则会出现错误 class Entity extends Backbone.Mode

Entity=newthemodel(#传入属性)

然后我可以扩展实体并维护模型属性/状态吗

class TheModel extends Backbone.Model
    foo: 
        #bar
编辑:

class User extends Entity
    foo: 
        super
        #more

不。让类扩展对象(而不是函数)没有意义。如果试图实例化
用户
类,则会出现错误

class Entity extends Backbone.Model
    initialize: (options) ->
        @_events options

        _events: (options) -> 
            entity.bind 'foo'

class Entity1 extends Entity
    _events: (options) ->  
        super options
        entity.bind 'bar'

class Entity2 extends Entity
    _events: (options) -> 
        super options
        entity.bind 'baz'

#a new entity arrives, we don't know if he is type one or two yet so he is...
entity = new Entity

#now we find out he is type 2
entity = new Entity2(entity.attributes)
如果要覆盖
实体
上的
foo
方法,则应直接覆盖,但请注意
super
语法不起作用。相反,你应该写作

TypeError: Cannot read property 'constructor' of undefined

对您的代码将正常工作,除了您将丢失绑定到
实体
的任何事件侦听器外,新的
实体
将不属于旧的
实体
所属的任何集合等。通常,您最好动态附加
foo
函数(如我的回答所示),或者抛弃多态性,转而使用一刀切的
foo
函数,如果@type为1,则执行类似
的操作…
entity.foo = ->
  @constructor::foo.apply arguments  # equivalent to super
  # ...