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

查看:83
本文介绍了具有多个属性的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,请记住

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天全站免登陆