Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

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.

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 
like image 964
Aaron Avatar asked Nov 12 '22 22:11

Aaron


1 Answers

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?

like image 146
Sal Rahman Avatar answered Nov 15 '22 00:11

Sal Rahman