功能组合:使用 Javascript 中的附加功能扩充现有功能

Function Composition: Augmenting an existing function with additional function in Javascript

我导入了一个带有函数的库,并想用一个将原始函数作为参数的函数和一个附加函数替换该函数。

原始函数可能是 logThis:

function logThis() {console.log('this'));

我可以创建一个新函数来执行 logThis 然后记录 'that';

function logThisThenThat() {
  logThis();
  console.log('that');
}

我想用一个执行原始函数然后执行另一个函数的新函数替换 logThis 吗?这可能与函数组合有关,还是我必须创建一个具有不同名称的新函数,该函数由原始函数和附加函数组成。

大致如下:

logThis = compose(logThis, logThat);

您可以用新函数覆盖现有函数。

像这样保留一份原件...

_logThis = logThis;

...然后让您的新版本调用原始版本...

function logThis() {
    _logThis();
    // your other function call or new code goes here
}

虽然这不是一个特别好的主意,因为这将修改 每个现有调用 对该方法所发生的情况。这需要小心处理。

此外,范围是这里的一个重要因素。这是您要执行的操作的基本示例。

如果将 logThis() 传递给 compose() 函数,您将在闭包中保留对它的引用,因此当您创建新的 logThis() 时它会继续存在。名称并不是那么重要,只要您重命名的顺序能让您在将名称指向新函数之前获得对旧 logThis() 的引用。例如,logThis = compose(logThis, logThat) 的右侧在下面的名称分配之前运行,因此您在重新分配名称之前捕获函数引用:

function logThis() {console.log('this')};
function logThat() {console.log('that')};

let compose = (f1, f2) => () => {
    f1()
    f2()
}

logThis = compose(logThis, logThat)
logThis()

您可以像这样创建一个函数。

function logThis() {
 console.log("this");
}

function logThat() {
 console.log("that");
}

let compose = (...func) => ()=> {
 let functions = func;
 functions.forEach((fn) => fn());
}

logThis = compose(logThis, logThat);
logThis();

添加(...func)作为参数,你可以执行3、4任意数量的函数like/need。

注意:编辑片段以匹配问题。 @mark-meyer 的 是正确的。