实现 new 方法

function myNew(func, ...args) {
    if (typeof func !== 'function') {
        return
    }
    let obj = Object.create(func.prototype)
    let result = func.apply(obj, args)
    // if (result instanceof Object) {
    //     return result
    // }
    if (result && (['function', 'object'].includes(typeof result))) {
        return result
    }
    return obj
}


function setName(name) {
    this.name = name
    console.log('设置name', name)
    return {
        des: '动物'
    }
}

const instance = new setName('cat')
console.log('正确的结果', instance)
const instance2 = myNew(setName, 'dog')
console.log('实现的结果', instance2)

你可能感兴趣的:(javascript,前端,开发语言)