new 操作会经过下面几个过程
- 1、创建一个新对象
- 2、设置原型 将对象的原型(proto) 设置成构造函数的原型 (prototype)对象
- 3、让函数的this 指向这个对象,执行构造函数中的代码 为这个对象添加新属性
- 4、判断函数的返回值类型,如果是值类型 返回创建的对象。如果是引用类型,就返回这个引用类型的对象
function F(){name: 'gdy'};
let f = new F();
console.log(f.name) // 'gdy'
实现:
function objectFactory() {
let newObject = null; // 创建一个新对象
let constructor = Array.prototype.shift.call(arguments); // 是为了要取出传入的构造函数 Function F
/** constructor 为
* function F(name){
this.name = name;
this.age = 18;
}
*/
let result = null;
// 判断参数是否是一个函数
if (typeof constructor !== "function") {
console.error("type error");
return;
}
// 新建一个空对象,对象的原型为构造函数的 prototype 对象
newObject = Object.create(constructor.prototype);
// console.log(newObject.__proto__ === constructor.prototype); //true
// 将 this 指向新建对象,并执行函数
// ↓ 之前 constructor 为 F{} this 指向之后为 F { name: 'gdy', age: 18 } ↓
result = constructor.apply(newObject, arguments); //argument 'gdy'
// console.log(constructor.toString());
// 判断返回对象
let flag = result && (typeof result === "object" || typeof result === "function");
// 判断返回结果
return flag ? result : newObject;
}
// 使用方法
function F(name){
this.name = name;
this.age = 18;
}
let newf = objectFactory(F,'gdy');
console.log(newf.name); // 'gdy'