Accessing the new constructor when call is defined

Get help with using AutoHotkey (v2 or newer) and its commands and hotkeys
iseahound
Posts: 1434
Joined: 13 Aug 2016, 21:04
Contact:

Accessing the new constructor when call is defined

Post by iseahound » 02 Oct 2022, 09:36

Is there a better way to access the new constructor when static call is defined?

Code: Select all

#Requires AutoHotkey v2.0-beta

Class MyClass {
   static call(a) {
      MsgBox a
   }

   __New(param1) {
      Tooltip param1
      return this
   }
}


a := {base: MyClass.prototype}.__New("it's about drive it's about power") ; Similar to v1 new
b := MyClass("it's about drive it's about power")

Sleep 3000
ExitApp

lexikos
Posts: 9560
Joined: 30 Sep 2013, 04:07
Contact:

Re: Accessing the new constructor when call is defined

Post by lexikos » 03 Oct 2022, 01:11

Why would you do that?

By default, MyClass inherits Call from Object. You can call it directly: (Object.Call)(MyClass, param1).

But generally if you are overriding Call, you should only be calling the superclass version from within the class: super(param1).

iseahound
Posts: 1434
Joined: 13 Aug 2016, 21:04
Contact:

Re: Accessing the new constructor when call is defined

Post by iseahound » 03 Oct 2022, 10:09

I found it to be useful to separate between a private constructor and a public user facing constructor. I first noticed that I could do this when I was writing wrapper functions to get rid of the new keyword in v1. It's not the best approach, as one could create a sub class and inherit from the main class and over writing its instance variables like in Java. Another approach would be to throw the extra arguments into **kwargs (keyword arguments/named parameters) and forget about them, if I was writing Python.

It is really interesting that __New allows parameters, even when shadowed or hidden by static call. I don't know if you designed it intentionally, or what languages have such a similar feature, but it does seem better (to me at least) to not spawn an extra class or use an extraordinary amount of named parameters which leads to annoying documentation (which params do I care about? which ones to ignore?), as in the case with Python.

lexikos
Posts: 9560
Joined: 30 Sep 2013, 04:07
Contact:

Re: Accessing the new constructor when call is defined

Post by lexikos » 03 Oct 2022, 22:48

__New is just a method that Object.Call calls. There is nothing special about it.

Post Reply

Return to “Ask for Help (v2)”