我试图弄清楚继承如何在Coffeescript中起作用。这是我的代码的简化示例:

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中的魔咒能够创建一个类是可变的类的新对象?

有帮助吗?

解决方案

没关系,我发现了:

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

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

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top