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;
}

 

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