要实现一个装饰器模式的函数来记录另一个函数的调用次数,我们可以定义一个高阶函数(即装饰器),它接受一个函数作为参数,并返回一个新的函数。这个新函数在每次被调用时,会更新和打印调用次数。 下面是一个具体的实现: ```javascript function callCounter(fn) { let count = 0; // 初始化调用计数器 return function(...args) { count++; // 每次调用时增加计数器 console.log(`called ${count} ${count === 1 ? 'time' : 'times'}`); // 输出调用次数 return fn.apply(this, args); // 调用原始函数并传递所有参数 }; } // 定义一个简单的函数 function sayHello(name) { console.log('hello ' + name); } // 使用装饰器包装函数 const sayHelloWithCounter = callCounter(sayHello); // 测试装饰后的函数 sayHelloWithCounter('Alice'); // 输出: called 1 time 和 hello Alice sayHelloWithCounter('Bob'); // 输出: called 2 times 和 hello Bob sayHelloWithCounter('Charlie'); // 输出: called 3 times 和 hello Charlie ``` 解释 1. callCounter 函数: - 接受一个函数 `fn` 作为参数。 - 创建一个闭包变量 `count` 来记录调用次数。 - 返回一个新的函数,该函数在每次被调用时: - 增加 `count` 的值。 - 打印当前的调用次数。 - 调用原始函数 `fn` 并传递所有参数。 2. sayHello 函数: - 这是一个简单的函数,接受一个名字并打印问候语。 3. sayHelloWithCounter: - 使用 `callCounter` 装饰器包装 `sayHello` 函数。 - 每次调用 `sayHelloWithCounter` 时,都会增加调用计数并打印当前的调用次数,然后执行 `sayHello` 函数。 通过这种方式,我们可以轻松地为任何函数添加调用次数的记录功能。 [2024-11-12 09:04:00 | AI写代码神器 | 478点数解答]