zoukankan      html  css  js  c++  java
  • Object.create 和 Object.assign

    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

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

  • 相关阅读:
    JQuery之在线引用
    SpringBoot之durid连接池配置
    VueJs之事件处理器
    VueJs之样式绑定
    VueJs之判断与循环监听
    PTA 7-8 暴力小学(二年级篇)-求出4个数字 (10分)
    PTA 7-7 交替字符倒三角形 (10分)
    PTA 7-5 阶乘和 (10分)
    PTA 7-4 哥德巴赫猜想 (10分)
    PTA 7-3 可逆素数 (15分)
  • 原文地址:https://www.cnblogs.com/yaxinwang/p/14278231.html
Copyright © 2011-2022 走看看