JS中new实现


js中通过new关键字去创建对象实例,原理如下:

  • 1.首先创建一个新对象
  • 2.根据原型链,设置空对象的__proto__为构造函数的prototype
  • 3.构造函数的this指向这个对象,执行构造函数
  • 判断函数的返回值类型,如果是引用类型,就返回这个引用类型对象
function myNew(context) {
  const obj = new Object();
  obj.__proto__ = context.prototype;
  const result = context.apply(obj, [...arguments].slice(1));
  return (typeof res === 'object' && res !== null) ? result: obj;
}


Leave a Reply

Your email address will not be published. Required fields are marked *