• 实现Object.create()


    Object.create() 语法

    Object.create(proto,[propertiesObject])
    

    参数

    • proto 在其上定义或修改属性的对象。

    • propertiesObject 要定义其可枚举属性或修改的属性描述符的对象。对象中存在的属性描述符主要有两种:数据描述符和访问器描述符(更多详情,请参阅 Object.defineProperties())。描述符具有以下键:

    第二个参数是为实例写入Object.defineProperties()的属性,这里顺带讲解下Object.defineProperties()

    Object.defineProperties() 使用示例

    let obj1 = { a: 2, b: 3 }
    
    Object.defineProperties(obj1, {
      a: {
        enumerable: false, // 数据、存储描述符号
        configurable: false, // 数据描述符
        writable: false, // 数据描述符
        value: 'xxx' // 数据描述符号
        get: function(){}, // 储存描述符
        set: function(){} // 储存描述符
      }
    })
    

    原生Object.create() 使用

    第一个传递null时,返回的实例原型为null

    第一个参数类型只能是object、function,否则报错。

    第二个参数类型,不能是null,否则报错

    第二个参数如果不为 undefined ,需要将其挂载到实例的 Object.defineProperties 上。

    let obj1 = { a: 2, b: 3 }
    
    let obj3 = Object.create('222', undefined) // TypeError: Object prototype may only be an Object or null: 222
    let obj2 = Object.create(obj1, null) // TypeError: Cannot convert undefined or null to object
    
    let obj2 = Object.create(obj1, { a: { enumerable: false } })
    console.log(obj2.a) // undefined
    
    

    手写实现

    // 第一个传递null时,返回的实例原型为null
    // 第一个参数类型只能是object、function,否则报错。
    // 第二个参数类型,不能是null,否则报错
    // 第二个参数如果不为 undefined ,需要将其挂载到实例的  Object.defineProperties 上。
    
    Object.mjy_create = function(proto, defineProperties) {
      if ( typeof proto !== 'object' && typeof proto !== 'function' ) {
        throw new TypeError(`Object prototype may only be an Object or null: ${proto}`)
      }
      if ( defineProperties === null ) {
        throw new TypeError('Cannot convert undefined or null to object')
      }
    
      function F(){}
      F.prototype = proto
      let obj = new F()
    
      if ( proto === null ) {
        obj.__proto__ = null
      }
      if ( defineProperties !== undefined ) {
        Object.defineProperties(obj, defineProperties)
      }
      return obj
    }
    
    let obj2 = Object.mjy_create(obj1, { a: { enumerable: false } })
    let obj3 = Object.create('222', undefined) // TypeError: Object prototype may only be an Object or null: 222
    let obj4 = Object.create(obj1, null) // TypeError: Cannot convert undefined or null to object
    console.log(obj2.a) // undefined
    
  • 相关阅读:
    ExpressGridPack 23 Crack
    常用数据分析方法笔记
    手摸手教你用AI生成PPT(本文不卖课)
    基于java校园二手物品交易系统计算机毕业设计源码+系统+lw文档+mysql数据库+调试部署
    2023年9月20日
    javaEE进阶 - Spring 更简单的读取和存储对象 - 细节狂魔
    JVM:垃圾收集器与内存分配策略(2)
    《吐血整理》保姆级系列教程-玩转Fiddler抓包教程(5)-Fiddler监控面板详解
    基于Spring Boot+MyBatis+MySQL的高校试卷管理系统
    对象字节输出流
  • 原文地址:https://blog.csdn.net/qq_45934504/article/details/127047382