0

I have a function handler:

function handler(data) {
    console.log(`1. ${data}`);
}

which I want to append, or redefine, in the same scope as follows:

let oldHandler = handler;
function handler(data) {
    oldHandler(data);
    console.log(`2. ${data}`);
}

such that when I now call handler:

handler("bar");

I expect the output to be:

1. bar
2. bar

Is this possible?

EDIT

Currently the above results in error: unknown: Identifier 'handler' has already been declared.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
ajrlewis
  • 2,968
  • 3
  • 33
  • 67
  • 1
    Because of hoisting `oldHandler` will reference the second declaration of `handler` and you'll end up with infinite recursion. – Titus Dec 03 '19 at 10:16

1 Answers1

1

Function declarations:

  • Declare a variable with a matching name
  • Are hoisted

Use a function expression instead. These do neither of the above.

function handler(data) {
  console.log(`1. ${data}`);
}

let oldHandler = handler;

handler = function handler(data) {
  oldHandler(data);
  console.log(`2. ${data}`);
};

handler("bar");
Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335