javascript - Coffeescript 类 mixin 不适用于构造函数

标签 javascript inheritance constructor coffeescript mixins

我有两个基类,如下所示(此示例已显着简化):

class Foo
  constructor: (@foo) ->

class Bar
  constructor: (@bar) ->

然后我还有两个类,通过扩展它们和添加功能来扩展/增强这些类:

class NewFoo extends Foo
  getFoo: ->
    @foo

class NewBar extends Bar
  getBar: ->
    @bar

但是,我也希望 NewFoo 和 NewBar 继承一个通用的构造函数/其他方法,例如

class Mixin
  constructor: (x) ->
    @history = 'something'
    super x

  getHistory: ->
    @history

我正在尝试让 Ne​​wFoo 和 NewBar 拥有 Mixin 构造函数和 getHistory 方法..

我尝试使用 CoffeeScriptcookbook mixin 示例:http://coffeescriptcookbook.com/chapters/classes_and_objects/mixins

mixOf = (base, mixins...) ->
  class Mixed extends base
  for mixin in mixins by -1 #earlier mixins override later ones
    for name, method of mixin::
      Mixed::[name] = method
  Mixed

因此 NewFoo/NewBar 变为:

class NewFoo extends mixOf Mixin, Foo
  getFoo: ->
    @foo

class NewBar extends mixOf Mixin, Bar
  getBar: ->
    @bar

但是这不起作用并失败并出现错误: 类型错误:无法读取未定义的属性“构造函数”

如何让 NewFoo/NewBar 继承常见的 Mixin 成员以及各自的基类?

编辑:

这是迄今为止我能想到的一切:

class Foo
  constructor: (@foo) ->

class Bar
  constructor: (@bar) ->

history = (base) ->
  class History extends base
    constructor: (param) ->
      @history = 'something'
      super param

    getHistory: ->
      @history
  History

class NewFoo extends history Foo
  getFoo: ->
    @foo

class NewBar extends history Bar
  getBar: ->
    @bar

newFoo = new NewFoo 'a foo'
console.log newFoo.getFoo()
console.log newFoo.history

最佳答案

你基本上是用 Mixin 来做到这一点:

class Mixin
  constructor:->
    super

如果你调用new Mixin();你会得到一个错误。您无法在不扩展任何内容的构造函数上调用 super。

mixOf 函数不能解决这个问题,它只是从其他对象复制方法并生成一个类。

关于javascript - Coffeescript 类 mixin 不适用于构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21816851/

相关文章:

java - 数据抽象和封装

javascript - 如果我们将 3 个参数传递给在 JavaScript 中用 2 个参数声明的函数,为什么我们不会出错

javascript - jQuery - 忽略双重 AJAX 调用?

c++ - 错误 : Invalid use of incomplete type

exception - 如何多次扩展 bundle ?

c# - Java 与 C# 方法/函数返回类型重写?

javascript - ES6 使用正则表达式过滤数组

javascript - React 事件处理程序、委托(delegate)

c++ - 如何区分 char 文字和 unsigned int 作为构造函数的参数

c++ - 构造函数完成运行时指针变为空