Search code examples
javascriptnode.jsmixins

Object.assign doesn't seem to work with Function.prototype


Trying to create a mixin, for a complex feature in a library.

This was working for me:

const proto = Object.create(Function.prototype);

but now I need to do some multiple inheritance such that an object inherits from both the Function prototype and the event emitter prototype, so I want to do this:

const EE = require('events');

const proto = Object.create(Object.assign({}, EE.prototype, Function.prototype));

but that was not working as expected.

So then I tried just this:

const proto = Object.assign({}, Function.prototype);

and that showed that for some reason the Function.prototype was not being copied, is my observation correct? Why would this be?


Solution

  • Per section 19.2.4.3 of the ES6 spec, the properties of Function.prototype are not enumerable and Object.assign() copies only enumerable properties. That explains why your copy ends up empty because Object.assign() didn't see any of the non-enumerable properties and thus didn't copy them.

    So, if you want to copy the properties, you will have to get the properties with something different. Object.create() is probably the best way to do it since that's what it was designed for.