简体   繁体   English

如何使用给定的原型链创建对象?

[英]How can I create an object with a given prototype chain?

I need a way to create an empty object whose prototype chain is provided as an array of objects:我需要一种方法来创建一个空对象,其原型链以对象数组的形式提供:

var prototypes = [{one: 1}, {two: 2}, {three: 3}];
var created = create(prototypes);
// prototype chain of created should be:
// created --> {one: 1} --> {two: 2} --> {three: 3}

How can I do this?我怎样才能做到这一点?

You basically can't (currently*), because there is only one prototype chain, prototypes are currently assigned only at object creation, and yet you have multiple discrete objects there that are unrelated.你基本上不能(目前*),因为只有一个原型链,原型目前只在对象创建时分配,但你有多个不相关的离散对象。 That is, to create the chain, you need each object in the chain to be backed by the previous one, but those aren't.也就是说,要创建链,您需要链中的每个对象都由前一个对象支持,但那些不是。

What you can do is create the chain with copies of those objects, but of course subsequent changes to those original objects wouldn't be reflected in the chain.可以做的是使用这些对象的副本创建链,但当然对这些原始对象的后续更改不会反映在链中。

You can get close with ECMAScript5 by creating new objects with getters and setters for all of the existing properties on those source objects and syncing them, but that wouldn't handle new properties (or deleted ones), just changes to existing properties.您可以通过为这些源对象上的所有现有属性创建带有 getter 和 setter 的新对象并同步它们来接近ECMAScript5,但这不会处理属性(或已删除的属性),只是更改现有属性。


* I said "currently" above because the current draft specification for the next ECMAScript version, ECMAScript 6th Edition, has a new Reflect object which has the ability to set a prototype on an existing object retrospectively. * 我在上面说“当前”是因为下一个 ECMAScript 版本(ECMAScript 6th Edition)的当前草案规范有一个新的Reflect对象,它能够回顾性地在现有对象上设置原型。 (Whereas with ECMAScript5 and earlier, you can only set an object's prototype when you're creating it.) So as of ES6, you'd be able to assemble those objects into a chain by using the future Reflect.setPrototypeOf method. (而在 ECMAScript5 和更早版本中,您只能在创建对象时设置它的原型。)因此,从 ES6 开始,您可以使用未来的Reflect.setPrototypeOf方法将这些对象组装成一个链。 But right now, cross-browser, you can't.但现在,跨浏览器,你不能。

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

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