模拟new实现

159 阅读1分钟
//模拟new的实现
function Animal(type) {
    this.type = type //实例上的属性
    //如果当前构造函数返回的是一个引用类型,需要把这个对象返回
    //return {name: 'jeffywin'}
}
Animal.prototype.say = function() {//原型上添加公共属性和方法
    console.log('say')
}

//let animal = new Animal('爬行动物') 
function myNew(fn, ...args) 
    { let obj = Object.create(fn.prototype);
    let res = fn.call(obj, ...args); 
    if (res && (typeof res === "object" || typeof res === "function"))
     { return res; } 
    return obj;
}

function newMy(){
        //Array.prototype.slice.apply(arguments).shift()
    //因为arguments是一个类数组对象,虽然他也有下标,但并非真正的数组,所以要操作[]    
    let Constructor = [].shift.call(arguments)//剩余的arguments就是其他参数
    let obj = {} // 返回的对象
    obj.__proto__ = Constructor.prototype // 原型上的方法
    let r = Constructor.apply(obj,arguments)
    return r instanceof Object ? r : obj // 判断是不是对象的实例,是就是引用类型
}

let animal = newMy(Animal,'爬行动物') 
animal.say()

image.png