我试图弄清楚咖啡脚本中的继承是如何工作的。这是我的代码的简化示例:
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 中有什么神奇的咒语能够创建一个类的新对象,其中类是可变的?