Add function or property to all Classes

Put simple Tips and Tricks that are not entire Tutorials in this forum
aliztori
Posts: 117
Joined: 19 Jul 2022, 12:44

Add function or property to all Classes

Post by aliztori » 30 Mar 2023, 20:59

I wanted to use an object function and I wanted to use the class's own method instead of using an external function,
Example:

Code: Select all


class SomeClass {
    static Call(arg) => MsgBox("Calling Call " arg) 
    static Method(arg) => MsgBox("Calling Method " arg)
}

SomeClass.Bind("method", "ali").Call()
; instead of 
ObjBindMethod(SomeClass , "method", "ali").Call()


but I had to make sure that the class itself has that method or not.
I couldn't write a unique method for all the classes I had, it's not dynamic and it's not correct.

I came to the conclusion that I can use this technique

Code: Select all

__ObjDefineProp := Object.Prototype.DefineProp
__ObjDefineProp(Class.Prototype, "Bind", {
    Call: (this, Method := 'Call', Params*) => ObjBindMethod(this, Method, Params*)
})
With this method, we can add a method to all the classes we created, isn't it great?
Instead of adding a method to all classes
Add that method to all classes with a few lines

And after all this, I created a method that you just need to add a method to this class so that it is added to all classes and include it in your main file.

Code: Select all

class ClassesMethod {
    
    static __New() {

        __ObjDefineProp := Object.Prototype.DefineProp
        for Prop in this.OwnProps()
			if SubStr(Prop, 1, 2) != "__"
				__ObjDefineProp(Class.Prototype, Prop, this.GetOwnPropDesc(Prop))

    }
    static Bind(Method := 'Call', Params*) => ObjBindMethod(this, Method, Params*)
    
}
It is clear that you can also use properties

Return to “Tips and Tricks”