具有多个属性的 Object.create() 的简写 [英] Shorthand for Object.create() with multiple properties

查看:20
本文介绍了具有多个属性的 Object.create() 的简写的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我想在 JavaScript 中创建一个对象,该对象具有指向另一个对象的原型链接,但有几个它自己的属性,我该怎么做?

If I want to create an object in JavaScript that has a prototype link to another object, but has several of it's own properties how can I do this?

var object1 = {
  a: 1,
  b: 2
};

var object2 = Object.create( object1 );
object2.c = 3;
object2.d = 4;

console.log( object2 ); // my new object with object1 as it's prototype link

我的挑战是我必须一次设置一个 object2 的属性.

My challenge here is that I have to set object2's properties one at a time.

我的另一个选择是:

var object1 = {
  a: 1,
  b: 2
};

var object2 = {
  c: 3,
  d: 4
};
    
Object.setPrototypeOf( object2, object1 );

console.log( object2 );

我上面的挑战是表现应该很糟糕.即, setPrototypeOf 很慢.https://jsperf.com/object-create-vs-object-setprototypeof

My challenge above is that the performance is supposed to be terrible. Namely, setPrototypeOf is slow. https://jsperf.com/object-create-vs-object-setprototypeof

当然,还有你提供的速记",writeableenumerable 以及 Object.create() 的所有内容,但这并不是真正的速记.

And then of course, there's the "shorthand" where you provide, writeable, enumerable and all that to Object.create(), but that's not really shorthand.

有什么想法吗?

推荐答案

作为 Object.assign 的替代方案,请记住 Object.create 接受带有要添加到的属性描述符的第二个参数对象:

As an alternative to Object.assign, remember Object.create accepts a second argument with the property descriptors you want to add to the object:

var object1 = {
  a: 1,
  b: 2
};
var object2 = Object.create(object1, {
  c: {value: 3, enumerable: true},
  d: {value: 4, enumerable: true}
});
console.log( object2 ); // my new object with object1 as it's prototype link

请注意,默认值是不可配置、不可写和不可枚举的.

Note the default is non-configurable, non-writable and non-enumerable.

如果这是一个问题,ES2017 引入了Object.getOwnPropertyDescriptors.

If that's a problem, ES2017 introduces Object.getOwnPropertyDescriptors.

var object1 = {
  a: 1,
  b: 2
};
var object2 = Object.create(object1, Object.getOwnPropertyDescriptors({
  c: 3,
  d: 4
}));
console.log( object2 ); // my new object with object1 as it's prototype link

这篇关于具有多个属性的 Object.create() 的简写的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆