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
59
Reaction score
29
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
2,362
Reaction score
1,854
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
59
Reaction score
29
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
9,228
Reaction score
6,007
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

Have you ever had the problem of not knowing how to name your game?
I tried to draw it to keep the aspect ratio of 48*48
It doesn't look good, but I'm not sure if there are other ways to render larger characters. and then maintain the sharpness or not
SF_Enemy1_6 added!
index.php

Just thought I'd share how my battlers are looking for my 4 main characters. From left to right... Ashlyn the brave fighter, Lizzabelle the peaceful mage, Suki the thief, Saedra the not-so-peaceful mage.

pLZHVLI.png
Power to the Game Make!

Forum statistics

Threads
118,780
Messages
1,118,648
Members
155,949
Latest member
lehma
Top