0

I was trying to figure this out with a friend.

Let's say you have a function like this:

const foo = function(i) { return function(j){ return 2 * j } };

How would I override foo with a different method?

Let's say I want to reuse foo with a different anonymous function that does something like function(j){ return 3 * j; };

How would I do that?

EDIT: I saw this post, but that's for variables. I'm asking specifically about anonymous methods.

EDIT 2: This is a proof of concept, so let's say that foo is a const and I can't turn it into a let

jeffkolez
  • 628
  • 3
  • 8
  • 31
  • You can't reassign a `const` since by definition they are constant. You could assign an object containing the function (`const foo = {method: function () {} }; foo.method = newFunction`), but at that point might as well use `let` instead of `const` – jfadich Feb 27 '19 at 23:09
  • It's a `const`ant - the whole point is to be readonly. – Jack Bashford Feb 27 '19 at 23:09
  • Loosely related to this question, but check out currying https://medium.com/@kbrainwave/currying-in-javascript-ce6da2d324fe . This technique allows you to compose functions and in this case, allow you to build multiple function where the parameter is multiplied by a different constant – mrQWERTY Feb 27 '19 at 23:12
  • *"I'm asking specifically about anonymous methods."* ... anonymous methods that are referred to by const variables. The same answers apply. You can create a new function all you want, but you can't replace the reference with the new function. – Kevin B Feb 27 '19 at 23:36

1 Answers1

0
  • const is used for constants, so it's not for overriding.
  • If you want to override your variable, use let or var

const constantFunction = x => x + 1;
let variableFunction = x => x + 2;

try {
  variableFunction = x => x + 3;
  console.log('Re-assigning to a variable: DONE');
} catch(e) {
  console.log('Error while re-assigning to a variable');
}

try {
  constantFunction = x => x + 3;
  console.log('Re-assigning to a constant: DONE');
} catch(e) {
  console.log('Error while re-assigning to a constant');
}
molamk
  • 4,076
  • 1
  • 13
  • 22