R
R
Rapen2016-09-12 16:36:39
JavaScript
Rapen, 2016-09-12 16:36:39

How did the wrapper access the element from the decorator function?

How does the wrapper get access to the cache object from the decorator, if, here, it doesn’t smell like a closure,

function f(x) {
  return Math.random()*x;
}


function makeCaching(f) {
  var cache = {}; 

  return function(x) {
    if (!(x in cache)) {
      cache[x] = f.call(this, x);
    }
    return cache[x];
  };

}

f = makeCaching(f);

var a = f(1);
var b = f(1);
alert( a == b ); // true (значение закешировано)

b = f(2);
alert( a == b ); // false, другой аргумент => другое значение

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Deodatuss, 2016-09-12
@Rapen

here the closure already carries)
we call makeCaching and redefine the function f. makeCaching, when executed, returns a new function that has a cache in the closure, this function decides whether to call the original function f (which is also in the closure) or get the value from the cache object

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question