How does this line work in the decorator?

  • 0
    Hello!
    I am learning JavaScript. The second day I can't figure out exactly how this line in the code works.

    slow = cachingDecorator (slow);

    Why, when we assign "slow" as an argument, the function "slow" itself continues to work in its original form? That is, why isn't it being reassigned? Does it have something to do with closure? Please tell me what this technique is called and what to google about this topic.

    function slow(x) {
      // здесь могут быть ресурсоёмкие вычисления
      alert(`Called with ${x}`);
      return x;
    }
    
    function cachingDecorator(func) {
      let cache = new Map();
    
      return function(x) {
        if (cache.has(x)) {    // если кеш содержит такой x,
          return cache.get(x); // читаем из него результат
        }
    
        let result = func(x); // иначе, вызываем функцию
    
        cache.set(x, result); // и кешируем (запоминаем) результат
        return result;
      };
    }
    
    slow = cachingDecorator(slow);
    
    alert( slow(1) ); // slow(1) кешируем
    alert( "Again: " + slow(1) ); // возвращаем из кеша
    JavaScript Keira Benitez, Jul 26, 2019

  • 3 Answers
  • 0
    To begin with, slow is reassigned. Initially, the function does something. and after that, caching is added before it.

    That is, after slow = cachingDecorator (slow); in slow Another function is found.



    is the "slow" function still working as it was?


    Because after the rewriting, slow contains a function that has access to the func variable (it stores the original functionality). And the new slow checks the cache and if it is empty starts func



    Sorry if I didn't explain it clearly :)
    Anonymous

  • 0
    yes, this is due to closure, at the time of the creation of the anonymous function, this anonymous function remembers external variables, in this case the slow function, which is stored in func, wherever this anonymous function is called, it calls the original slow function. Read it from Cantor.
    Anonymous

  • 0
    Why, when we assign "slow" as an argument, does the "slow" function itself continue to work in its original form?


    therefore:

    let result = func (x); // otherwise, call the function
    Anonymous

Your Answer
To place the code, please use CodePen or similar tool. Thanks you!