【问题标题】:Coffeescript Inheritance: Static variables/methodsCoffeescript 继承:静态变量/方法
【发布时间】:2015-05-16 10:24:10
【问题描述】:

在其他OOP语言中,以下是一种常见的抽象形式

class AbstractClass
  myVar: null

  @doSomething: ->
    console.log myVar

class Child extends AbstractClass
  myVar: 'I am a child'

调用 Child.doSomething() 应该打印“我是孩子”。 我还应该能够将 Child.doSomething 作为回调传递并让它打印相同的内容。我已经尝试了 with 或 w/o @ 的所有组合,使用分号和等于来定义 myVar,我无法弄清楚。在 CoffeeScript 中执行此操作的正确方法是什么?

编辑

我认为我过度简化了我的示例,因为我无法让它工作(进一步编辑:现在使用此解决方案)。这是真正的代码(使用建议的解决方案):

class AbstractController
  @Model: null

  @index: (req, res) ->
    console.log @
    console.log @Model
    @Model.all?(req.params)

class OrganizationController extends AbstractController
  @Model: require "../../classes/community/Organization"

在我的路由文件中

(express, controller) ->
  router = express.Router({mergeParams: true})
  throw new Error("Model not defined") unless controller.Model?
  console.log controller
  router
  .get "/:#{single}", _.bind(controller.show, controller)
  .get "/", _.bind(controller.index, controller)
  .post "/", _.bind(controller.post, controller)

将 OrganizationController 传递给此函数会正确记录 OrganizationController 对象,所以我知道它已经到达那里:

{ [Function: OrganizationController]
  Model: { [Function: Organization] ...},
  index: [Function],
  __super__: {} }

但是当我到达那条路线时,两个 console.log 调用会打印出来

{ [Function: AbstractController]
  Model: null,
  index: [Function] }
null

我得到一个错误:“无法读取属性‘全部’为空”

【问题讨论】:

    标签: inheritance express coffeescript


    【解决方案1】:

    您错过了一些@s。以下打印I am a child:

    class AbstractClass
      @myVar: null
    
      @doSomething: ->
        console.log @myVar
    
    class Child extends AbstractClass
      @myVar: 'I am a child'
    
    Child.doSomething()
    

    但是如果要作为回调函数传递,则需要绑定到Child:

    callf = (f) ->
      f()
    
    callf Child.doSomething                # prints undefined
    callf Child.doSomething.bind(Child)    # prints I am a child
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-07
      • 2012-07-17
      • 2012-11-21
      • 1970-01-01
      • 2011-02-13
      • 2016-09-10
      • 2017-01-10
      • 2019-04-28
      相关资源
      最近更新 更多