Last active
January 9, 2023 21:37
-
-
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`. Существующие классы не портятся, используются их "пр…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
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
Example of use: