手写js的new方法

function New(fn, ...args) {
    
    
  let obj = Object.create(fn.prototype);
  let res = fn.apply(obj, args);
  return res instanceof Object ? res : obj;
}

测试代码:

function Dog(name) {
    
    
  this.name = name;
}
Dog.prototype.sayName = function () {
    
    
  console.log(this.name);
};
let newDog = New(Dog, "只是New出来的小狗");
newDog.sayName();

おすすめ

転載: blog.csdn.net/weixin_43595755/article/details/118298236