[OOP] How can I use this.method as a label for Menu commands from within a __new() constructor?

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
TacticalMook
Posts: 3
Joined: 10 Jul 2020, 03:12

[OOP] How can I use this.method as a label for Menu commands from within a __new() constructor?

Post by TacticalMook » 01 Oct 2022, 00:58

I am trying to assign an instance of Foo.bar() [ ie: this.bar() ] as the target label for Menu commands.

The commented-out version of class Foo runs and behaves as I would like the first version of Foo to run. I am trying to get this behavior without using class variables in the first version, but run into compilation or logical errors.

Using this.bar in line 10 doesn't compile. Using Foo.bar compiles, but I think it changes the behavior of this in bar() at line 18, making this.qux reference the empty class variable Foo.qux instead instead of the instance variable foobar.qux

Code: Select all

#SingleInstance Force
#Persistent
foobar := new Foo

class Foo {
	qux := "default"
	
	__New() {
		this.qux := "Thud"
		Menu, Tray, Add, Thud, this.bar
		Menu, Tray, Add
		Menu, Tray, NoStandard
		Menu, Tray, Standard
		return this
	}
	
	bar() {
		MsgBox % this.qux
	}
}

;class Foo {
;	static qux := "default"
;	
;	__New() {
;		Foo.qux := "Thud"
;		Menu, Tray, Add, Thud, Foo.bar
;		Menu, Tray, Add
;		Menu, Tray, NoStandard
;		Menu, Tray, Standard
;		return this
;	}
;	
;	bar() {
;		MsgBox % Foo.qux
;	}
;}

teadrinker
Posts: 4309
Joined: 29 Mar 2015, 09:41
Contact:

Re: [OOP] How can I use this.method as a label for Menu commands from within a __new() constructor?

Post by teadrinker » 01 Oct 2022, 03:14

Code: Select all

      handler := ObjBindMethod(this, "bar")
      Menu, Tray, Add, Thud, % handler
But what the point of using the __New() method? Are you going to have several instances of this class?

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

Re: [OOP] How can I use this.method as a label for Menu commands from within a __new() constructor?

Post by lexikos » 01 Oct 2022, 05:55

Do yourself a favour and switch to AutoHotkey v2. ;)

v2 translation
Using Foo.bar compiles
You mean it runs without showing an error message, and seems to work. This is because the function created by the method definition happens to be named "Foo.bar", and happens to be added to the script's list of functions in a way that you can reference it by name. This is undocumented, so you shouldn't rely on it.

Also, this is just a parameter; when the Menu calls the "method", it passes the item name as the first parameter. So this is just a string, not an object.

teadrinker
Posts: 4309
Joined: 29 Mar 2015, 09:41
Contact:

Re: [OOP] How can I use this.method as a label for Menu commands from within a __new() constructor?

Post by teadrinker » 01 Oct 2022, 07:33

lexikos wrote: Do yourself a favour and switch to AutoHotkey v2.
Happy when the release comes out. :)

Post Reply

Return to “Ask for Help (v1)”