2

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

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:无法读取未定义的属性'foo'。

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

4

1 回答 1

2

没关系,我想通了:

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

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

于 2011-01-06T19:38:16.857 回答