# initCloneObject
# Description
初始化对象克隆,会创建并返回一个 继承了 传入 object 原型链的对象
# Params
{Object} object
# Return
Object
# Depend
import isPrototype from './isPrototype.js'
# Code
function initCloneObject(object) {
return (typeof object.constructor === 'function' && !isPrototype(object))
? Object.create(Object.getPrototypeOf(object))
: {}
}
# Analyze
- 首先判断
object.constructor是否为function,如果为function,则表示object上可能存在原型链,同时传入的object不能是 原型对象 - 如果存在
object.constructor, 使用Object.getPrototypeOf获取object的原型属性,拿到原型属性后, 使用Object.create创建一个 和object原型链相同的对象 - 否则返回一个空对象
# Remark
- Object.prototype.constructor MDN (opens new window)
- Object.getPrototypeOf() MDN (opens new window)
- Object.create() MDN (opens new window)
# Example
function A () {}
const b = new A
const c = initCloneObject(b)
console.log(b.__proto__ === c.__proto__) // true
← Hash isFlattenable →