Object.create(proto,[propertiesObject])
proto 在其上定义或修改属性的对象。
propertiesObject 要定义其可枚举属性或修改的属性描述符的对象。对象中存在的属性描述符主要有两种:数据描述符和访问器描述符(更多详情,请参阅 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(){} // 储存描述符
}
})
第一个传递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