使用Object.create()和Object.assign()创建对象有什么区别? [英] What is difference between creating object using Object.create() and Object.assign()?

查看:403
本文介绍了使用Object.create()和Object.assign()创建对象有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下代码:

var obj1 = Object.create({}, {myProp: {value: 1}});
var obj2 = Object.assign({}, {myProp: 1});

obj1 和<之间是否有任何区别code> obj2 因为每个对象都是以不同的方式创建的?

Is there any difference between obj1 and obj2 since each object has been created in a different way?

推荐答案

让我们在此代码中比较 obj1 obj2

Let's compare obj1 and obj2 in this code:

var target1 = {}, target2 = {};
var obj1 = Object.create(target1, {myProp: {value: 1}});
var obj2 = Object.assign(target2, {myProp: 1});

原型链

Object.create 使用指定的[[Prototype]]创建一个新对象,并使用 Object.assign 分配直接在指定对象上的属性:

Object.create creates a new object with the specified [[Prototype]], and Object.assign assigns the properties directly on the specified object:

obj1 !== target1;
obj2 === target2;

obj1 和<$的原型链c $ c> obj2 看起来像

obj1 --> target1 -->  Object.prototype --> null
obj2 -------------->  Object.prototype --> null

属性

Object.create 定义属性, Object.assign 仅指定它们。

Object.create defines properties and Object.assign only assigns them.

创建属性时,赋值会将其创建为可配置,可写和可枚举。定义属性时,可以指定这些标志,但默认情况下它不可配置,也不可写且不可枚举。

When creating a property, assignments will create it as configurable, writable and enumerable. When defining a property, you can specify those flags, but by default it's not configurable, nor writable and not enumerable.

Object.getOwnPropertyDescriptor(obj1, 'myProp');
  // { value: 1, writable: false, enumerable: false, configurable: false }
Object.getOwnPropertyDescriptor(obj2, 'myProp');
  // { value: 1, writable: true, enumerable: true, configurable: true }

这篇关于使用Object.create()和Object.assign()创建对象有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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