Given some javascript like this:
var doSomething = function() { return 1 };
doSomething.someProperty = "a";
How can I redefine the function so that, e.g., doSomething() returns 2, but without losing any additional properties defined on it?
I've found plenty of answers about this sort of thing for OOP, but I'm not using "new" here, just calling the function directly.
You can assign the properties from the original function to a new function:
Original Answer:
function redefineFunction(oldFn, newFn) {
Object.assign(newFn, oldFn);
return newFn;
}
// Original function and properties
var doSomething = function() { return 1 };
doSomething.someProperty = "a";
// Redefine
doSomething = redefineFunction(doSomething, function() { return 2 });
console.log(doSomething);
console.log(doSomething());
console.log(doSomething.someProperty);
Simplified using Object.assign without needing a function:
var doSomething = function() {
return 1
};
doSomething.someProperty = "a";
// Redefine
doSomething = Object.assign(function() {return 2}, doSomething);
console.log(doSomething);
console.log(doSomething());
console.log(doSomething.someProperty);
You could do something like this:
var doSomething = function() {
return doSomething.returnVal;
}
doSomething.returnVal = 1; // Without this, doSomething returns undefined
console.log(doSomething()); // <= 1
doSomething.returnVal = 2;
console.log(doSomething()); // <= 2
If you want to make some more dramatic change to the function (i.e. altering the algorithm that it runs rather than just a data value within it), then probably the best approach would be to create an entirely new function and copy the properties of your old function to it:
function copyProperties(source, destination) {
for (var property in source) {
destination[property] = source[property];
}
}
var doSomething = function() {
return 1;
}
doSomething.someProperty = "a";
var doSomethingElse = function() {
return 2;
}
copyProperties(doSomething, doSomethingElse);
console.log(doSomethingElse()); // <= 2
console.log(doSomethingElse.someProperty); // <= a
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With