装饰器模式

 1 function slow(x) {
 2   // 这里可能会有重负载的 CPU 密集型工作
 3   alert(`Called with ${x}`);
 4   return x;
 5 }
 6 
 7 function cachingDecorator(func) {
 8   let cache = new Map();
 9 
10   return function(x) {
11     if (cache.has(x)) {    // 如果缓存中有对应的结果
12       return cache.get(x); // 从缓存中读取结果
13     }
14 
15     let result = func(x);  // 否则就调用 func
16 
17     cache.set(x, result);  // 然后将结果缓存(记住)下来
18     return result;
19   };
20 }
21 
22 slow = cachingDecorator(slow);
23 
24 alert( slow(1) ); // slow(1) 被缓存下来了
25 alert( "Again: " + slow(1) ); // 一样的
26 
27 alert( slow(2) ); // slow(2) 被缓存下来了
28 alert( "Again: " + slow(2) ); // 和前面一行结果相同

slow函数:显示一条信息并返回一个数字x

装饰器函数接收一个函数作为参数

定义一个Map对象cache

cache.has(x)     x是键,如果存在返回true

cache.get(x)      通过键返回值

func(x)               表面上是“作为形参的函数”被调用了,实际上就是实参函数被调用了,这里传入的是slow,slow函数显示一条信息并返回x,用一个变量result将slow函数返回的x接收住。

原文地址:https://www.cnblogs.com/flyover/p/14151332.html