简体   繁体   English

Object.assign似乎不适用于Function.prototype

[英]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: 但是现在我需要做一些多重继承,这样一个对象既可以继承Function原型,也可以继承事件发射器原型,所以我想这样做:

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? 这表明由于某种原因未复制Function.prototype,我的观察正确吗? Why would this be? 为什么会这样呢?

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. 根据ES6规范的19.2.4.3节, Function.prototype的属性不可枚举,而Object.assign()仅复制可枚举的属性。 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. 这就解释了为什么您的副本最终为空,因为Object.assign()没有看到任何不可枚举的属性,因此也没有复制它们。

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. Object.create()可能是执行此操作的最佳方法,因为这正是它的设计目的。

@jrfiend00 is probably right about this. @ jrfiend00可能是正确的。 It appears I am able to achieve what I want to do, like so: 看来我能够实现自己想做的事情,就像这样:

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

A two-step mixin. 两步混合。

Normally, I would expect to be able to do this: 通常,我希望能够做到这一点:

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

but that doesn't work, most likely for the reason jfriend00 specified. 但这不起作用,很可能是由于jfriend00指定的原因。 Not sure why the spec allows Object.create to work for this though. 不确定为什么规范允许Object.create为此工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM