JS中,new 操作符具体干了什么?
new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象类型之一。
一、过程:
new 共经历了4个过程。
var fn = function () { };
var fnObj = new fn();
1、创建了一个空对象
var obj = new object();
2、设置原型
obj.__proto__ = fn.prototype;
3、让 fn 的 this 指向 obj ,并执行 fn 的函数体
var result = fn.call(obj);
4、判断 fn 的返回值类型,如果是值类型,返回 obj 。如果是引用类型,就返回这个引用类型的对象。
if (typeof(result) === "object"){  
    return result;  
} else {  
    return obj;
}  
二、手写实现
function objectFactory() {
  let newObject = null,
    constructor = Array.prototype.shift.call(arguments), // 取出第一个参数--构造函数
    result = null;
  // 参数判断
  if (typeof constructor !== "function") {
    console.error("type error");
    return;
  }
  // 新建一个空对象,对象的原型为构造函数的 prototype 对象
  newObject = Object.create(constructor.prototype);
  // 将 this 指向新建对象,并执行函数
  result = constructor.apply(newObject, arguments);
  // 判断返回对象
  let flag =
    result && (typeof result === "object" || typeof result === "function");
  // 判断返回结果
  return flag ? result : newObject;
}
// 使用方法
// objectFactory(构造函数, 初始化参数);

 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号