【发布时间】: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