myNew------new实现------

152 阅读1分钟
function Fo1(name) {
    this.name = name
}
function Fo2(name) {
    this.name = name
    return {
        name: 'return Self value'
    }
}
function New(Constr) {
    if (typeof Constr !== "function") {
        throw new Error('No constructors have been detected!')
    }
    var obj = Object.create(Constr.prototype)
    var args = Array.prototype.slice.call(arguments, 1) //Get parameters
    var res = Constr.apply(obj, args) //Execute the constructor to mount properties
    if(res == null) return obj
    return Object.prototype.toString.call(res) == '[object Object]' ? res : obj
}
let f1 = New(Fo1, 'test')
let f2 = New(Fo2, 'test')
console.log(f1.name)
console.log(f2.name)