In my code, an array is declared from an imported module. Functions related to this module are imported from the second module. Here is a simplified version of my code:
The first module containing an array
let module1 = {}; module1.array = [10, 20, 30];
The second module containing functions
var module2 = {}; module2.fct1 = () => { return array[0]; }; module2.fct2 = () => { return array[1]; }; module2.fct3 = () => { return array[2]; };
I want to merge these two modules into one entity:
module1.fct1 = module2.fct1; module1.fct2 = module2.fct2; module1.fct3 = module2.fct3;
module1
Now contains arrays and functions
{ array: [10, 20, 30], fct1: () => { return array[0]; }, fct2: () => { return array[1]; }, fct3: () => { return array[2]; } }
However, when I call the function, the array seems to be outside the scope of the function:
console.log (module1.fct1())
I got the following error:
Uncaught reference error: array is undefined
If I create a single module containing the array and the function in the same file, it works.
My question is: Is there a way in JavaScript to merge two modules. My ultimate goal is to pass the merged module to another function.
This is a JSFiddle link: https://jsfiddle.net/Imabot/rxsfvgda/4/
P粉2540777472023-09-10 10:43:41
It looks like the part you expected module2
is a method that can be called on any other (module) object that has the .array
property. To do this, you need to access the array via this.array
, and you need to use method syntax instead of arrow functions:
var module2 = {}; module2.fct1 = function() { return this.array[0]; }; module2.fct2 = function() { return this.array[1]; }; module2.fct3 = function() { return this.array[2]; };
or simpler writing:
var module2 = { fct1() { return this.array[0]; }, fct2() { return this.array[1]; }, fct3() { return this.array[2]; }, };