RMMZ [Solved] A JS question about storing functions in an array

Status
Not open for further replies.

Sepheyer

Veteran
Veteran
Joined
Jul 20, 2021
Messages
74
Reaction score
39
First Language
English
Primarily Uses
RMMZ
JS allows storing functions in an array and calling them later. For me the problems start when those functions are on instances of a class and when I need to refer to the instances via "this.".

I created a test snippet illustrating what I am trying to accomplish, but I clearly lack the syntax knowledge to get me the result since the code errors out on runtime. In the case of the test code, the output should be: "One Two".

Whoever helps with finding a way of storing object instance functions in an array - I am wishing you much great karma. Live long and prosper!

JavaScript:
class test{
    constructor(name){          
        this._name = name
    }
 
    report_name(){
        console.log(this._name)
    }
}

const t1 = new test('One')
const t2 = new test('Two')

var arr = [t1.report_name, t2.report_name]
arr.forEach((x) => {x()})


The context for the question -- in Python I use arrays with functions inside Subscriber class. And I was hoping there is a similarly simple mechanism to store delegates in JS.
 
Last edited:

Eliaquim

Hakuen Studio
Veteran
Joined
May 22, 2018
Messages
3,177
Reaction score
2,437
First Language
Portuguese - Br
Primarily Uses
RMMZ
Hi there!

You can try to use the bind method to store the "this" scope on the functions:

var arr = [ t1.report_name.bind(t1), t2.report_name.bind(t2) ]

Bind Method

Or, you could instead put on the array only the t1 and t2:

JavaScript:
var arr = [t1, t2]
arr.forEach( (x) => { x.report_name() } )
 

Sepheyer

Veteran
Veteran
Joined
Jul 20, 2021
Messages
74
Reaction score
39
First Language
English
Primarily Uses
RMMZ
@Eliaquim you are a lifesaver, thank you very much!!! Live long and prosper!
 

slimmmeiske2

Little Red Riding Hood
Global Mod
Joined
Sep 6, 2012
Messages
10,114
Reaction score
6,398
First Language
Dutch
Primarily Uses
RMXP

This thread is being closed, due to being solved. If for some reason you would like this thread re-opened, please report this post and leave a message why. Thank you.

 
Status
Not open for further replies.

Latest Threads

Latest Posts

Latest Profile Posts

Today is my Birthday, LOLOL!
I just hope I get to see the Mario movie while I'm in Fort Myers next week. I'm super hyped! Anyone else planning to see it when it comes out?
Brace yourself. We are approaching that time of the year again.
I once said, "I definitely want to be done with this project before my 40th birthday." At the time, I was about 50% done with the project.

With under 365 days to go now, I'm about ... 30% done.

What a sweet, innocent fool I was.
can anyone tell me how to edit my pfp it isn't obvious and I'm new here

Forum statistics

Threads
129,990
Messages
1,206,811
Members
171,233
Latest member
soskso
Top