NodeJS:深层复制一个函数

是否有可能在NodeJS中深入复制一个函数对象? 我试图使用一个函数,我已经设置了字段,但我需要一种方法来复制该函数,以便当我复制它时,我可以分别修改这些额外的字段。

例如:

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 

我已经尝试了使用下划线/ lodash的东西,但他们似乎将函数转换为克隆中的对象。 在前面的例子中, b会被认为是{ __var: 1 } 。 我需要能够执行function的深层复制..

我使用的另一种方法是.bind()函数(产生函数的一个副本),但不绑定任何实际的参数。 如果函数具有静态方法/属性,则可以使用Object.assign将其复制。 我这样做的用例是整体Notification构造函数。 例:

 // 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'); 

对于更简单的用例, bind可能会起作用,例如:

 function hi(name) { console.log('hey ' + name); } var newHi = hi.bind(); newHi('you'); //=> 'hey you' 

通过执行以下操作,我能够实现所需的function:

 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 

使用lodash的_.assign(dest,src)

 let a = function(){console.log('hello world')} a.__var = 1 

然后..

 let b = () => 42; _.assign(b,a); b.__var // returns 1 b() // returns 42