手写new操作符

1.流程

  • 创建一个全新的对象
  • 将这个对象的 [[Prototype]] 链接到构造函数的 prototype 属性
  • 将新对象作为 this 上下文执行构造函数
  • 如果构造函数返回一个对象,则返回该对象;否则返回新创建的对象

2.代码

function newFunc(func,...args){
      // 检查构造函数是否为函数
  if (typeof func !== 'function') {
    throw new TypeError('func must be a function');
  }
    //1创建对象
    const obj={};
    // 2原型设置
    Object.setPrototypeOf(obj,func.prototype);
    // 或者
   //  obj.__proto__=func.prototype;
    // 1和2可以直接使用Object.create(func.prototype);创建一个空对象,且proto指向第一个参数
    
    // 3改变this指向
    const result = func.apply(obj,args);
    //apply改变this指向后原函数会立即执行,且此方法只是临时改变this指向一次
    // 4. 判断构造函数返回值是否为对象(非原始值、null)
  // 如果构造函数返回了一个对象,则返回该对象
  // 否则返回新创建的对象
  return result != null && 
           typeof result === 'object' ? result : obj;
    
}
posted @ 2026-01-18 12:47  DurianTRY  阅读(0)  评论(0)    收藏  举报