实现一个new操作符
new操作符会返回一个对象,即构造函数当中的this,它可以访问构造函数原型上的属性以及方法
function create(Con, ...args) {
    this.obj = {};//创建一个空的对象
    //将空对象指向构造函数的原型链
    Object.setPrototypeOf(obj, Con.prototype);
    //obj绑定到构造函数上,便可以访问构造函数中的属性
    let result = Con.apply(obj, args);
    //如果返回的result是一个对象则返回该对象,new方法失效,否则返回obj
    return result instanceof Object ? result : obj;
}

function Test(name, age) {
    this.name = name;
    this.age = age;
}

let test = create(Test, 'yin', 20);
console.log(test.name);//yin
console.log(test.age);//20

 

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-01-03
  • 2022-12-23
  • 2021-10-18
  • 2021-09-29
  • 2022-01-27
  • 2021-07-25
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-12-12
  • 2022-02-04
相关资源
相似解决方案