objectCreate - 创建对象

122 阅读1分钟

概念描述

  • 创建对象的一种方式,传入原型和实例属性配置。
  • 先创建一个空对象,设置其原型和实例属性。

代码实现

/**
* @description: Object.create
* @author: huen2015
*/

function customCreate(proto: object | null, properties?: PropertyDescriptorMap): any {
    if (typeof proto !== 'object') {
        console.warn(`Object prototype may only be an Object or null: ${proto}`)
        return
    }

    const obj = {}
    Reflect.setPrototypeOf(obj, proto)
    if (properties) {
        Object.defineProperties(obj, properties)
    }
    return obj
}

function Fn(this: any) {
}

Fn.prototype.say = function () {
    console.log('say hello')
}

const properties: PropertyDescriptorMap = {
    name: {
        value: 'huen2015',
        configurable: true,
        writable: true,
        enumerable: false
    },
    sex: {
        value: '20',
        configurable: false,
        writable: false,
        enumerable: false
    }
}
const customCreateResult = customCreate(Fn.prototype, properties)
customCreateResult.name = 'huen2016'
// customCreateResult.sex = '21'
console.log('customCreateResult', customCreateResult)

代码演示仓库