【问题标题】:CoffeeScript class inheritanceCoffeeScript 类继承
【发布时间】:2011-06-04 20:34:21
【问题描述】:

我试图弄清楚咖啡脚本中的继承是如何工作的。这是我的代码的简化示例:

class Parent

  constructor: (attrs) ->
    for own name,value of attrs
      this[name] = value

Parent.from_json_array = (json, callback) ->
  for item in JSON.parse(json)
    obj = new ChildA item  # [1]
    callback obj

class ChildA extends Parent

class ChildB extends Parent

ChildA.from_json_array("[{foo: 1}, {foo: 2}]") (obj) ->
  console.log obj.foo

我需要在标有[1] 的行上添加什么才能在此处使用正确的子类?这可行,但只创建具有ChildA 原型的对象。我尝试过类似的方法:

Parent.from_json_array = (json, callback) ->
  klass = this.prototype
  for item in JSON.parse(json)
    obj = klass.constructor item  # [1]
    callback obj

...但这会使obj 在我的回调函数中未定义(TypeError: Cannot read property 'foo' of undefined"。

CoffeeScript 中有什么神奇的咒语能够创建一个类的新对象,而该类是可变的?

【问题讨论】:

    标签: prototypal-inheritance coffeescript


    【解决方案1】:

    没关系,我想通了:

    Parent.from_json_array = (json, callback) ->
      klass = this
      for item in JSON.parse(json)
        obj = new klass item
        callback obj
    

    原来你可以只new 一个存储在变量中的类。我以为我以前尝试过,但是遇到了语法错误。

    【讨论】:

      猜你喜欢
      • 2013-03-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-03
      相关资源
      最近更新 更多