使用原型链从多个类扩展Backbone类

时间:2013-08-05 13:36:14

标签: javascript backbone.js coffeescript

我遇到了一种扩展Backbone对象的非标准或不寻常的方式  通过建立原型链。

方案:
  - Child类继承自两个超类
  - 两个超级班级无关   - 因此SuperB = SuperA.extend不适用

例如: 从ChildC范围,SuperA.prototype.initialize.apply按预期工作。

然而如何扩展ChildC,以便在ChildC范围内提供SuperA类方法A. 使用prototype.initialize.apply类比?

SuperA = Backbone.Model
  defaults:
    flagA: false
  initialize: ->
    this.set "flagA", true
    console.log "SuperA::initialize()"
  methodA: ->
    console.log "methodA"

SuperB = Backbone.Model.extend
  defaults:
    flagB: false
  initialize: ->
    this.set "flagB", true  
    console.log "SuperB::initialize()"
  methodB: ->
    console.log "methodB"


ChildC = Backbone.Model.extend
  defaults:
    flagC: false
  initialize: ->
    SuperA.prototype.initialize.apply this, arguments 
    SuperB.prototype.initialize.apply this, arguments
    this.set "flagC", true
    console.log "ChildC::initialize()"
  methodC: ->
    console.log "methodC"


instanceA = new SuperA()
instanceA.methodA()

instanceB = new SuperB()
instanceB.methodB()

instanceC = new ChildC()
instanceC.methodC()

console.log instanceC.get("flagA")
console.log instanceC.get("flagB")
console.log instanceC.get("flagC")

instanceC.methodC()

Gist的链接 链接到JS Bin

0 个答案:

没有答案