简体   繁体   中英

Proper Way to Reference Variables in Javascript

I'm currently refactoring my code and I want to export an object array called REFERENCE_LIST to another file.

reference.js

export const REFERENCE_LIST = [
 {name:"TypeA", foodList:foodAList}, 
 {name:"TypeB", foodList:foodBList}
]

export const foodAList = ['apple', 'orange', 'banana']
];

export const foodBList = ['meat', 'fish']
];

However, the foodList field from REFERENCE_LIST is always "undefined". Am I referencing these arrays incorrectly?

You cannot reference variables in JS. You can reference object values, though - but those objects need to be created first for that:

export const foodAList = ['apple', 'orange', 'banana'];
export const foodBList = ['meat', 'fish'];

export const REFERENCE_LIST = [
  {name:"TypeA", foodList:foodAList}, 
  {name:"TypeB", foodList:foodBList}
];

You might also use getters where the order of creation doesn't matter:

export const REFERENCE_LIST = [
  {name:"TypeA", get foodList() { return foodAList; }}, 
  {name:"TypeB", get foodList() { return foodBList; }}
];

But even those will throw an exception when you evaluate them before the constants are initialised.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM