【问题标题】:How can I call a method defined in one CoffeeScript mixin from another mixin on the same object?如何从同一个对象上的另一个 mixin 调用一个 CoffeeScript mixin 中定义的方法?
【发布时间】:2015-10-10 21:31:30
【问题描述】:

我有一个包含两个 mixin 的 CoffeeScript 对象:

namespace 'S.Graphs', (exports) ->
  class exports.DocketEvents extends Module
    @extend Scatter
    @extend Axis

    name: 'DocketEvent'

    constructor: ({@litigation}) ->
      console.log("Building view of docket events for #{@litigation.name}")

如何从另一个 mixin 中调用定义在一个 mixin 中的方法?我希望如果我在一个 mixin 中定义了一个方法,我可以从另一个 mixin 中调用它:

window.Scatter =
  extended: ->
    @include

      dimensions: ->
        Justly.view.dimensions()

但我不能,因为这会引发 this.dimensions 不是函数的异常。

怎么会?

另外,如果我没有以 window. 作为前缀定义我的 mixin,我似乎无法将它用作 mixin - 解决这个问题的最佳方法是什么?

【问题讨论】:

  • 你需要 window. 前缀的原因是,coffeescript 将每个文件包装在 IIFE 中。您要么需要通过模块系统导出类,要么将其附加到全局对象。
  • 关于从同一个对象上的另一个 mixin 调用一个 mixin 的方法有什么想法吗?
  • 很难说没有比您发布的更多代码了。通常,如果我在做一个 mixin,我会使用一个类似 mixin = (obj, mixes...) -> mixes.forEach((mix) -> Object.keys(mix).forEach((key) -> obj[key] = mix[key])); return obj 的辅助函数。然后我只是用类原型作为第一个值和 mixin 对象作为第二个值来调用它。如果 mixins 是函数而不是对象,我会使用 OtherConstructor.apply(SomeClass.prototype, args)

标签: javascript coffeescript mixins


【解决方案1】:

虽然这并不能直接回答您提出的问题,但我相信它会为您提供解决潜在问题的工具。我最近遇到了一种情况,我必须创建几个类,每个类都继承自 google maps 构造函数。但是为了干燥我自己的代码,我希望所有这些类也从抽象基类继承它们的通用功能。这或多或少是我想出的(例如简化的):

mixin = (obj, mixes...) ->
    mixes.forEach (mix) ->
        Object.keys(mix).forEach (key) -> obj[key] = mix[key]
    return obj

class MyBaseClass
    constructor: () ->
        #init some vars

    method1: () -> #do stuff
    method2: () -> #do stuff

class Signal extends google.maps.Marker
    constructor: () ->
        super()                            #adds google maps goodness
        MyBaseClass.apply(this, arguments) #inits the vars
        @type = 'signal'

    signalMethod1: () -> #do stuff

#add base class methods. Messing directly with class prototypes is considered by
#some to be something of an antipattern in coffeescript, but it achieves the 
#desired effect here.
mixin Signal.prototype, MyBaseClass.prototype

您可能必须调整每个派生类的构造函数中的应用程序顺序(对 super 的调用是在应用 MyBaseClass 构造函数之前还是之后?其他构造函数表达式呢?)但启用多重继承。多重继承通常比它的价值更麻烦,但有时是最好的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-09
    • 2019-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-23
    相关资源
    最近更新 更多