js implements the extend function

defineProperty is used to define or modify the properties of the object value. Through defineProperty, you can set the readable and writable properties of the property.
getOwnPropertyName can be used to get all properties on the object (including non-enumerable properties)

// 定义
Object.defineProperty(Object.property, 'extend', {
    
    
	writable: true, // 可写
	enumerable: false, // 可枚举
	configurable: true, // 可设置
	value: function (o) {
    
     // 值
		// 获取o的所有属性名称
		const names = Object.getOwnPropertyName(o)
		for (let i = 0, len = names.length; i < len; i++) {
    
    
			// 判断对象中是否已经存在属性
			if (names[i] in this) continue
			// 获取o中的属性设置
			const desc = Object.getOwnPropertyDescriptor(o, names[i])
			Object.defineProperty(this, name[i], desc)
		}
	}
})
// 实例
let a = {
    
    
	itemA: 1
}
Object.defineProperty(a, 'itemB', {
    
    
	writable: true,
	enumerable: false,
	configurable: true,
	value: 2
})
console.log(a) // {itemA: 1, itemB: 2}
let b = {
    
    }
b.extend(a)

Guess you like

Origin blog.csdn.net/m0_38038767/article/details/109720954