0

Here's a JavaScript object I'm working with:

const tree = {
  birdhouse: {
    inspectNest: () => 'eggs'
  },
  ...
}

I want the world to have access to the inspectNest function tucked into the middle there, but for hand-wavy reasons I do not want to give my consumers the entire tree object. I was hoping I could do something like this as a named export:

export { tree.birdhouse.inspectNest as inspectNest };

However, including the dot notation to access those properties seems to be invalid syntax.

I suspect a destructuring statement like const { birdhouse: { inspectNest }} = tree; right before exporting may work, but there's another hitch - other parts of my program may redefine birdhouse or inspectNest as the app runs. When that happens, I don't know if the changed item will continue to be exported with the new value.

Any advice, or is destructuring the best approach?

(P.S. I know export const inspectNest = tree.birdhouse.inspectNest; will do the trick, but in my real app I'd need many of these assignment exports. If at all possible, I want to use the named export object to keep things syntactically cleaner.)

  • `export const inspectNest = tree.birdhouse.inspectNest;` seems to be the only option. Or go the other way round: `export function inspectNest() { return 'eggs'; }; const tree = { birdhouse: {inspectNest}};`. – Felix Kling Dec 06 '18 at 21:55
  • There are probably times you want this, but it's generally more JavaScript-y to export a closure over the stuff you don't want others to see. But you could `bind` the method to the instance and then export. – Jared Smith Dec 06 '18 at 22:01

0 Answers0