可以在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我尝试过使用下划线/存档,但它们似乎将函数转换为克隆中的一个对象。在前面的示例中,b最终将成为{ __var: 1 }。我需要能够对这个函数执行一次深入的复制。
发布于 2016-06-05 01:05:39
我使用过的另一种方法是.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'发布于 2016-06-05 00:38:26
通过执行以下操作,我能够实现所需的功能:
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发布于 2016-06-05 07:44:18
let a = function(){console.log('hello world')}
a.__var = 1然后..。
let b = () => 42;
_.assign(b,a);
b.__var // returns 1
b() // returns 42https://stackoverflow.com/questions/37636144
复制相似问题