Is it possible to deep copy a function object in NodeJS? I am trying to use a function that I have set fields on, but I need a way to copy that function so that when I do duplicate it, I can modify these extra fields separately.
For example:
let a = function(){console.log('hello world')}
a.__var = 1
let b = clone(a)
a.__var // 1
b.__val // 1
b.__var = 2
a.__var // 1
I've tried things like using underscore/lodash, but they seem to convert the function to an object in the clone. b would wind up being { __var: 1 } in the previous example. I need to be able to perform a deep copy on the function..
Another approach to this that I've used is to .bind() the function (which produces a copy of the function) but not bind any actual arguments. If the function has static methods/properties on it, you can use Object.assign to copy those on. My use case for doing this was shimming the global Notification constructor. Example:
// copy the constructor
var NotifConstructor = Notification.bind(Notification);
//assign on static methods and props
var ShimmedNotif = Object.assign(function (title, _opts) { /* impl here that returns NotifConstructor */ }, Notification);
//now you can call it just like you would Notification (and Notification isn't clobbered)
new ShimmedNotif('test');
For simpler use cases, bind will probably work, e.g.:
function hi(name) { console.log('hey ' + name); }
var newHi = hi.bind();
newHi('you'); //=> 'hey you'
I was able to achieve the desired functionality by doing the following:
let a = function (){console.log('hello world')}
a.field = 'value'
// Wrap the "cloned" function in a outer function so that fields on the
// outer function don't mutate those of the inner function
let b = function() { return a.call(this, ...arguments) }
b.field = 'different value'
console.log(a.field === b.field) // false
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