Can you alter a Javascript function after declaring it?

You can do all kinds of fun stuff with javascript, including redefining functions:

let a = function() { return 1; }
console.log(a()); // 1
    
// keep a reference
let old = a;
   
// redefine
a = function() {
  // call the original function with any arguments specified, storing the result
  const originalResult = old.apply(old, arguments);
  // add one
  return originalResult + 1;
};

console.log(a()); // 2

Voila.

Edit: Updated to show this in a crazier scenario:

let test = new String("123");
console.log(test.toString()); // logs 123
console.log(test.substring(0)); // logs 123
String.prototype.substring = function(){ return "hahanope"; }
console.log(test.substring(0)); // logs hahanope

You can see here that even though “test” is defined first, and we redefine substring() afterwards, the change still applies.

Side note: you really should reconsider your architecture if you’re doing this…you’re going to confuse the crap out of some poor developer 5 years down the road when s/he’s looking at a function definition that’s supposed to return 1, but seems to always return 2….

Leave a Comment