Reputation: 3247
I'm trying to override Node.js require function. However in JavaScript functions can have values and properties
Assuming code like this
a = function() {};
a.someParam1 = 1;
a.someParam2 = 2;
If I console log it. It'd look like:
{ [Function] someParam1: 1, someParam2: 2 }
I know I can call this function by simply doing
a()
But what If I wanted to override it's behavior without getting rid of properties?
Doing
a = function(){ console.log("Some other function")}
console.log(a.someParam1)
would yield undefined.
How can I override function value without touching it's parameters?
Upvotes: 2
Views: 67
Reputation:
The function object is the function. The function is not some kind of property of an abstract object whose "value" (the function) can be overridden. You cannot override the value of a function any more than you can override the number 1 with the number 2.
You can attach properties to the function, being an object, but the function is the function and cannot be changed out from underneath itself.
I don't know in what environment a console.log
would print out { [Function] someParam1: 1, someParam2: 2 }
. It certainly does not in any environment I'm familiar with. console.log
on a function, with or without associated properties, would print out the function.
> a = function() {};
> a.someParam1 = 1;
> a.someParam2 = 2;
> console.log(a)
function () {}
If you want to move the properties onto a different function, feel free with Object.assign(function newFunc() { }, oldFunc)
or _.extend
or whatever you prefer.
Upvotes: 1
Reputation: 2188
You can inherit, but that's not recommended*. (But since what you want to do isn't recommended in the first place you might as well give it a shot.)
a = function() {return "something"};
a.someParam1 = 1;
a.someParam2 = 2;
a = Object.setPrototypeOf(function(){return "something else";},a);
*Warning: Mutating the [[Prototype]] of an object, using either this method or the deprecated Object.prototype.__proto__, is strongly discouraged, because it is very slow and unavoidably slows down subsequent execution in modern JavaScript implementations. source: MDN
Upvotes: 1
Reputation: 3831
a = (function(previously) {
var newImplementation = function() {
// new implementation
}
for (var x in previously) {
newImplementation[x] = previously[x];
}
return newImplementation;
})(a);
Upvotes: 1