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 中的魔法咒语是什么?创建一个类的新对象,其中该类是变量?
I'm trying to figure out how inheritance works in coffeescript. Here's a simplified example of my code:
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
What do I need to put on the line marked [1]
to use the correct child class here? This works, but only creates objects with a prototype of ChildA
. I've tried something like:
Parent.from_json_array = (json, callback) ->
klass = this.prototype
for item in JSON.parse(json)
obj = klass.constructor item # [1]
callback obj
... but this leaves obj
as undefined in my callback function (TypeError: Cannot read property 'foo' of undefined".
Whats the magic incantation in CoffeeScript to be able to create a new object of a class, where the class is variable?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
没关系,我想通了:
原来你可以
new
一个存储在变量中的类。我以为我以前尝试过这个,但遇到了语法错误。Nevermind, I figured it out:
Turns out you can just
new
a class stored in a variable. I thought I had tried this before, but was getting a syntax error.