Using mixins instead of inheritance

Post your working scripts, libraries and tools for AHK v1.1 and older
iseahound
Posts: 1444
Joined: 13 Aug 2016, 21:04
Contact:

Using mixins instead of inheritance

18 Nov 2018, 22:55

A mixin is like a shared basket of functions that other classes can enjoy. To import a collection of functions and static variables (sorry no instance variables) use the code below.

A mixin in a nested class.

Code: Select all

q := new uber.b
q.test()

try MsgBox % "Ground Level: " ObjRawGet(q, "__class")                 " Number of Objects: " q.Count()
try MsgBox % "Level -1: " ObjRawGet(q.base, "__class")                " Number of Objects: " q.base.Count()
try MsgBox % "Level -2: " ObjRawGet(q.base.base, "__class")           " Number of Objects: " q.base.base.Count()

for i, j in q
   MsgBox % i " : " j

class uber {
class b {
   mixin := this.__Mixin("a") ; NOTE THE STRING "a"

   __Mixin(name){
      try object := IsObject(name) ? name : %name%

      if !IsObject(object) {
         if ((_class := RegExReplace(this.__class, "^(.*)\..*$", "$1")) != this.__class)
            Loop, Parse, _class, .
               outer := (A_Index=1) ? %A_LoopField% : outer[A_LoopField]
         object := outer[name]
      }

     ; Import functions and data from the object.
      __class := this.__class
      for reference, subobject in object {
         MsgBox % reference
         if IsFunc(subobject)
            this.base[reference] := ObjBindMethod(object, reference)
         else
            this[reference] := subobject
      }
      this.__class := __class

     ; Delete the mixin property (optional.)
      self_remove := ObjBindMethod(this, "Remove", "mixin")
      SetTimer, % self_remove, -1
   }
}

class a {
   test() {
      MsgBox % "Foxy diva Jennifer Lopez wasn't baking my quiche."
   }
}
}
The line mixin := this.__Mixin(name) is required. The argument can be an object or a string. If it is an object it can be a prototype object, or a class super global. If it is a string, then it will dereference to an object. It is recommended to use a string instead of a class name, because the string can be dereferenced inside a nested class, while the object will throw an error.

Continued from... https://autohotkey.com/boards/viewtopic.php?f=6&t=54475 where I foolishly used inheritance even though it wasn't needed!

Return to “Scripts and Functions (v1)”

Who is online

Users browsing this forum: No registered users and 195 guests