简体   繁体   English

有没有办法根据Coffeescript中的超类值在原型上定义一个对象?

[英]Is there a way to define an object on the prototype based on the super class value in Coffeescript?

Question

Let's say I have the following class in CS 假设我在CS中有以下课程

class Foo
  foo:
    one: 1
    two: 2

I'd like to have a class Bar extends Foo whose foo property returned {one: 1, two: 2, three: 3} . 我想要一个class Bar extends Foofoo属性返回{one: 1, two: 2, three: 3} Is there a way I can do this in the class definition for Bar where I am only appending three: 3 to the already existing foo property on the superclass Foo ? 有没有办法可以在Bar的类定义中执行此操作,其中我只将three: 3附加到超类Foo上已存在的foo属性中?

Use case / work around 用例/解决方法

I'm curious if it is possible to do something like I've explained above. 我很好奇是否有可能像我上面解释的那样做。 However, due to my use case it is not a blocking issue since I can use Coffeescript's super call to work around it by making it a function. 但是,由于我的用例,它不是阻塞问题,因为我可以使用Coffeescript的super调用来解决它,使它成为一个函数。

I'm currently using Backbone and I have two classes. 我目前正在使用Backbone,我有两个类。 One inherits from Backbone.Model and the other inherits from the first class. 一个继承自Backbone.Model ,另一个继承自第一个类。 In the first class I'm setting the defaults property so that when this model is created, it has instance variables set if they're not passed in. The class inheriting from my first class has one additional key value pair to add to this defaults object though it would be the same situation if I wanted to overwrite a default. 在第一个类中,我设置了defaults属性,这样当创建这个模型时,如果它们没有被传入,它就会设置实例变量。从我的第一个类继承的类有一个额外的键值对要添加到这个defaults虽然如果我想覆盖默认值,它会是相同的情况。

The object's default values in Backbone are obtained by using Underscore's result method so the quick work around in this case is to simply make defaults a function that returns the same object. Backbone中对象的默认值是通过使用Underscore的result方法获得的,因此在这种情况下快速解决方法是简单地使defaults成为返回同一对象的函数。 In Coffeescript this is incredibly easy and becomes: 在Coffeescript中,这非常容易,变成:

class Foo
  foo: ->
    one: 1
    two: 2

And then in Bar you can do the following: 然后在Bar您可以执行以下操作:

class Bar extends Foo
  foo: ->
    _.extends super, three: 3 

Although, in CoffeeScript, the super keyword is strictly used to call the parent method, the language doesn't seem to hide away the __super__ "static" variable. 虽然在CoffeeScript中,super关键字严格用于调用父方法,但该语言似乎并未隐藏__super__ “static”变量。 Let's use it to our full advantage. 让我们充分利用它。

class Bar extends Foo
  foo: _.extend @__super__.foo, three: 3

The @ in the above class definition is pointing to the Bar constructor. 上面类定义中的@指向Bar构造函数。 Bar 's __super__ property seems to be referring to an instance of Foo . Bar__super__属性似乎指的是Foo一个实例。

I wonder why doesn't CoffeeScript just treat super like another this keyword, but for referring to the super class instance? 我不知道为什么不CoffeeScript的只是把super像另一个this的关键字,但指的是超类的实例?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM