1


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

场景:
- 子类继承自两个超类
- 两个超类不相关
- 因此 SuperB = SuperA.extend 不适用

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

然而,如何使用prototype.initialize.apply 类比扩展ChildC 以便在ChildC 范围内使用SuperA 类methodA

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

4

0 回答 0