new的作用

168 阅读1分钟

new的过程做了哪些事

  • 调用这个函数
  • 创建一个空对象( 函数对象 )
  • 让函数中的this指向这个新对象 ( 创建出来的对象绑定this )
  • 默认返回这个对象 ( 即:创建的实例就是return的对象 )
  • 默认返回this对象
    • return 1; //如果手动添加返回不是对象,不影响this
    • return fn; //如果手动返回一个对象,响应this
   实现一个简单的new方法
function Parent(age,name){
    this.age = age;
    this.name = name;
}
Parent.prototype.getDetail = function(){
    return this.name + "," + this.age;
}
function newChild(Parent,...ages){
    let child = Object.create( Parent.prototype );
    Parent.apply( child, ages );
    return child;
}

const child = newChild(Parent, "李四", 18);
child.getDetail()