JS ES6:如何让子方法访问他们的兄弟姐妹?

JS ES6: How to give child methods access to their sibblings?

我有多种实用方法,例如

export const makeTextUtils = ({ U }) =>
  Object.freeze({
    hello: () => "Hello World!",
    lorem: () => "Lorem ipsum..."
  )};

这些子实用程序可以相互引用

export const makeOutputUtils = ({ U }) =>
  Object.freeze({
    logHello: () => console.log(U.txt.hello())
  )};

现在我想在 utils.js 中公开 Utils 并将父方法注入所有子方法

import { makeTextUtils } from './text';
import { makeOutputUtils } from './output';

// dependency injections
const textUtils = makeTextUtils({ U });
const outputUtils = makeTextUtils({ U });

// building parent util method
export const U = Object.freeze({
  txt: textUtils,
  out: outputUtils
});

我试过各种方法来导入主文件顶部的 U 并调换文件内的顺序,但似乎没有任何效果。

如有任何帮助,我们将不胜感激。

首先在顶部声明 U 对象,以便您可以将其传递给其他函数。然后,在U得到分配给它的属性后,就可以冻结它了:

import { makeTextUtils } from "./text";
import { makeOutputUtils } from "./output";

export const U = {};

// dependency injections
const textUtils = makeTextUtils({ U });
const outputUtils = makeOutputUtils({ U });

// building parent util method
Object.assign(U, {
  txt: textUtils,
  out: outputUtils
});
Object.freeze(U);

U.out.logHello();

https://codesandbox.io/s/happy-benz-cu3n5

在对象内部传递 U 并立即在实用函数中对其进行解构似乎没有任何作用 - 除非有特殊原因,请随意传递 U 对象(并单独使用 U 参数)。