Object Oriented

Hush provides basic support for object oriented programming. This means you can write object oriented code in Hush, but the language won’t give you fancy features for free. Objects can be modeled through dictionaries, using keys as accessors and values as member data and methods. To ease the use of dictionaries as objects, Hush provides the self keyword, which is described in the functions section.

  1. # This function acts like a combination of a class and a constructor. It'll take any
  2. # arguments relevant to the construction of a `MyCounter` object, and will return an
  3. # instance of such object, which is nothing but a dictionary.
  4. let MyCounter = function(start)
  5. @[
  6. # A member field. Using the same convention as Python, a field starting with an
  7. # underscore should be considered private.
  8. _start: start,
  9. # A method. Here, we can use the `self` keyword to access the object.
  10. get: function()
  11. self._start
  12. end,
  13. # Another method.
  14. increment: function()
  15. self._start = self._start + 1
  16. end,
  17. ]
  18. end
  19. let counter = MyCounter(1) # object instantiation.
  20. std.print(counter.get()) # 1
  21. counter.increment()
  22. std.print(counter.get()) # 2

Inheritance

Single inheritance can be implemented using a similar technique:

  1. # A derived class.
  2. let MySuperCounter = function (start, step)
  3. # Instantiate an object of the base class. We'll then augment this object with
  4. # derived functionality.
  5. let counter = MyCounter(start)
  6. counter._step = step # Add new fields to the object.
  7. # Override a method. Make sure not to change the number of parameters here!
  8. counter.increment = function ()
  9. self._start = self._start + self._step
  10. end
  11. # In order to override a method and call the parent implementation, you'll need to
  12. # bind it to the current object, and then store it to a variable:
  13. let super_get = std.bind(counter, counter.get)
  14. counter.get = function()
  15. let value = super_get() # call the parent method.
  16. std.print(value)
  17. value
  18. end
  19. counter
  20. end
  21. let super_counter = MySuperCounter(2, 3)
  22. super_counter.get() # 2
  23. super_counter.increment()
  24. super_counter.get() # 5