[v2 - a108][Tips] How to create a Class property for instances of a class.
Posted: 29 Apr 2020, 09:03
TLDR
Prerequisites.
Classes and static __new.
Introduction and examples.
Sometimes we want to refer to a static method or property when we use an instance of a class. We can do this by directly referring to the class through its super global variable. This implies a few problems, we need to hard-code class names and and we need to consider variable scope. Example,
Code: Select all
class x {
static prop := 'A'
g() {
msgbox x.prop
}
}
instance_of_x := x.new()
instance_of_x.g ; A
Code: Select all
class y extends x {
static prop := 'B'
}
Code: Select all
g() {
if this is x
msgbox x.prop
else if this is y
msgbox y.prop
}
Code: Select all
g() {
msgbox this.Class.prop
}
How to setup a Class property for instances of a class.
Simply add one line to the super class' static __new method,
Code: Select all
static __new() => this.prototype.Class := this
Code: Select all
class x {
static __new() => this.prototype.Class := this
static prop := 'A'
g() {
msgbox this.Class.prop
}
}
class y extends x {
static prop := 'B'
}
instance_of_x := x.new()
instance_of_y := y.new()
instance_of_x.g ; A
instance_of_y.g ; B
Exercises.
1) Explain some of the limitation and issues with using %this.__class% vs. the proposed this.Class property. Hint, some have already been mentioned above.
2) Create a Class property which takes one integer parameter to access super-classes, i.e., complete the code below,
Code: Select all
class x {
}
class y extends x {
}
class z extends y {
}
instance_of_z := z.new()
msgbox instance_of_z.class == z ; 1
msgbox instance_of_z.class[1] == y ; 1
msgbox instance_of_z.class[2] == x ; 1
Cheers.