我叫大王来巡山

导航

 

Object.assign(target, ...source)

1.Object.assign方法只会拷贝源对象自身(不包括原型)的并且可枚举的属性到目标对象,使用源对象的get和目标对象的set,所以会调用相关getter和setter。

通俗点说:源对象的属性值需要配置可枚举,enumerable为true,目标对象的属性值需要可写,writable为true才可以进行拷贝。如果目标对象不可写入,则会TypeError

String类型和 Symbol 类型的属性都会被拷贝。mdn地址:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Object/assign

 

为了将属性定义(包括其可枚举性)复制到原型,应使用Object.getOwnPropertyDescriptor()Object.defineProperty() 。使用这两个方法,可以拷贝属性描述器

// 说明源对象的属性需要是可枚举的
const target = { a: 1, b: 2 } const source = { a: 2 } Object.defineProperty(source, 'b', { // 不可枚举 value: 3 }) Object.assign(target, source) console.log(target)// {a: 2, b: 3}
// 说明目标对象的属性,需要是可写入的
const target = { a: 1 } const source = { a: 2, b: 3 } Object.defineProperty(target, 'b', { // 不可写 value: 2 }) Object.assign(target,source) // TypeError: Cannot assign to read only property 'b' of object '#<Object> console.log(target)
// 说明原型上的属性,不会进行拷贝
const target = { a: 1 } function Test () { this.a = 2, this.b = 3 } Test.prototype.c = 2 const source = new Test() Object.assign(target,source) console.log(source) console.log(target)

Object.create(proto, propertiesObject)

var obj = Object.create({
  _a: 3
}, {
  a: {
    value: 4,
    enumerable: true,
    writable: true,
    configurable: true
  }
})
console.log(obj)

第一个参数为原型对象 obj.__proto__ = proto

第二个参数为对象自身的属性:属性描述器

 

posted on 2021-01-17 16:21  我叫大王来巡山  阅读(218)  评论(0编辑  收藏  举报