Let's say I have the following class in 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}
. 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
?
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.
I'm currently using Backbone and I have two classes. One inherits from Backbone.Model
and the other inherits from the first class. 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.
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. In Coffeescript this is incredibly easy and becomes:
class Foo
foo: ->
one: 1
two: 2
And then in Bar
you can do the following:
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. 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
's __super__
property seems to be referring to an instance of Foo
.
I wonder why doesn't CoffeeScript just treat super
like another this
keyword, but for referring to the super class instance?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With