(1)首先创建了一个新的空对象
(2)设置原型,将对象的原型设置为函数的 prototype 对象。
(3)让函数的 this 指向这个对象,执行构造函数的代码(为这个新对象添加属性)
(4)判断函数的返回值类型,如果是值类型,返回创建的对象。如果是引用类型,就返回这个引用类型的对象。
function objectFactory() {let newObj = {}//拿到第一个参数,不能使用arguments.filter,因为arguments是一个类数组,没有该函数let constructor = Array.prototype.filter.call(arguments)let result = null;// 判断参数是否是一个函数if (typeof constructor !== "function") {console.error("type error");return;}// 新建一个空对象,对象的原型为构造函数的 prototype 对象newObj = Object.create(constructor.prototype);//改变this指向,执行构造器中的代码result = constructor.apply(newObj, arguments);// 判断返回对象let flag = result && (typeof result === "object" || typeof result === "function");// 判断返回结果return flag ? result : newObj;
}function Fn(name){this.name = name
}objectFactory(Fn,'aDong')