Can you extend initialized models?

馋奶兔 提交于 2019-12-12 00:33:38

问题


class TheModel extends Backbone.Model
    foo: 
        #bar

Entity = new TheModel(#pass in attributes)

Can I then extend Entity and maintain the models attributes/state?

class User extends Entity
    foo: 
        super
        #more

EDIT:

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)

回答1:


No. Having a class extend an object (rather than a function) doesn't make sense. If you tried to instantiate your User class, you'd get the error

TypeError: Cannot read property 'constructor' of undefined

If you want to override the foo method on Entity, you should do so directly, though note that the super syntax won't work. Instead, you should write

entity.foo = ->
  @constructor::foo.apply arguments  # equivalent to super
  # ...


来源:https://stackoverflow.com/questions/7394992/can-you-extend-initialized-models

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!