2、new的實現原理

 模擬new的實現

function Animal(type){
    this.type=type;   //實例上的屬性
    //如果當前構造函數 返回的是一個引用類型,需要把這個對象返回
    // 函數
    return {name:'message'}
}
Animal.prototype.say=function (){
    console.log('say');
}
let animal=mockNew(Animal,'哺乳類');
console.log(animal.type);
animal.say();
function mockNew(){
    //Constructor ==> animal  剩餘的arguments 就是其他的參數
    let Constructor=[].shift.call(arguments);
    let obj={};   //返回的結果
    obj.__proto__=Constructor.prototype;   //原型上的方法
    let r=Constructor.apply(obj,arguments);
    return r instanceof Object ? r:obj;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章