简单实现一个new操作符

77 阅读1分钟

前端中new的作用是什么

new操作符号用来创建一个基于原油对象的实例或者构造函数内置的实例对象

函数举例

function  Mynew(target,...argutmets){
  // 1.创建空对象
  const Obj =  {};
  //2.将对象原型指目标函数的原型
  Obj.__proto__ = target.prototype;
  //3.将构造函数中的this指向新建对象
  let res  = target.apply(Obj,argutmets);
  //返回对象
  return Object.prototype.toString.call(res) === '[object Object]' ? res : Obj;

}

测试

function  hj(name,age)
{
  this.name = name;
  this.age = age;
  console.log(name)
}
let child = Mynew(hj,'lisi',18);
console.log(child,90);

打印结果如下:

截屏2024-03-02 14.40.53_副本.png

注意最后返回的对象一定要经过判断其类型,如果直接是返回res函数将无法进行得到最后的值,只能是undefined