1

I was studying on JS Decorators and don't understand how the wrapper is able to access the inner functions argument. The snippet works, but I don't understand why the anonymous function 'function(val)' gets access to val, the argument of slow().

// https://codepen.io/lideebe/pen/VOjGvb

// simple function that gets wrapped
function slow(x){
  return x * 3;
}

// the wrapper function
function cacheDecorator(func){

  return function(val){ // How does this anonymous function get access to val?
    return func(val)
  }

}

// do the wrap
slow = cacheDecorator(slow);

// call the function
console.log(slow(2));

Output is 6 and that is correct.

Peter-L
  • 107
  • 7
  • Javascript closures at work. – chamoda May 12 '19 at 13:47
  • 2
    The first example in the dup should clarify things for you. But essentially `cacheDecorator` returns a function, so `slow` is set to the inner anonymous function, which can be called using `slow(2)` – Nick Parsons May 12 '19 at 13:48

1 Answers1

0

It's because cacheDecorator returns a function which takes a parameter val, and when you call that returned function with the value 2, it just gets accessed like normal. So slow, after you reassign it, is:

slow = function(val) {
  return val * 3;
}

So val is used as the parameter for the argument passed when the newly wrapped function is called.

Jack Bashford
  • 43,180
  • 11
  • 50
  • 79