Skip to content

Instantly share code, notes, and snippets.

@darky
Last active January 9, 2023 21:37
Show Gist options
  • Save darky/75d6a6a4d431e7182888 to your computer and use it in GitHub Desktop.
Save darky/75d6a6a4d431e7182888 to your computer and use it in GitHub Desktop.
Multiple inheritance in Coffeescript. This little helper make proper prototype chain and call `super`. Existing classes in chain not violated, uses theirs "projections". Мультинаследование в Coffeescript. Этот маленький хелпер создаёт корректную цепочку прототипов с правильным вызовом `super`. Существующие классы не портятся, используются их "пр…
virtual_class = (classes...)->
classes.reduceRight (Parent, Child)->
class Child_Projection extends Parent
constructor: ->
# Temporary replace Child.__super__ and call original `constructor`
child_super = Child.__super__
Child.__super__ = Child_Projection.__super__
Child.apply @, arguments
Child.__super__ = child_super
# If Child.__super__ not exists, manually call parent `constructor`
unless child_super?
super
# Mixin prototype properties, except `constructor`
for own key of Child::
if Child::[key] isnt Child
Child_Projection::[key] = Child::[key]
# Mixin static properties, except `__super__`
for own key of Child
if Child[key] isnt Object.getPrototypeOf(Child::)
Child_Projection[key] = Child[key]
Child_Projection
@darky
Copy link
Author

darky commented Aug 15, 2014

Example of use:

class My extends virtual_class A, B, C

Copy link

ghost commented Oct 17, 2015

I made some tests for this library.
Child class doesnt contain any of parent.prototype variables. Also inheritance works well only for last virtual_class argument. Here you can see some tests i made https://github.com/Snowshield/mixins.coffee

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment