ajrlewis
ajrlewis

Reputation: 3058

Appending to / redefining a function?

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.

Upvotes: 0

Views: 51

Answers (1)

Quentin
Quentin

Reputation: 943527

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");

Upvotes: 1

Related Questions