JavaScript new 操作符具体干了什么呢?如何实现?
new 操作符具体干了什么?
// (1)首先创建了一个新的空对象
// (2)设置原型,将对象的原型设置为函数的 prototype 对象。
// (3)让函数的 this 指向这个对象,执行构造函数的代码(为这个新对象添加属性)
// (4)判断函数的返回值类型,如果是值类型,返回创建的对象。如果是引用类型,就返回这个引用类型的对象。
new共经历了四个过程。
| 12
 3
 
 | var fn = function () { };var fnObj = new fn();
 
 
 | 
1、创建了一个空对象
2、设置原型链
| 1
 | obj._proto_ = fn.prototype
 | 
3、让fn的this指向obj,并执行fn的函数体
| 1
 | var result = fn.call(obj);
 | 
4、判断fn的返回值类型,如果是值类型,返回obj。如果是引用类型,就返回这个引用类型的对象。
| 12
 3
 4
 5
 
 | if (typeof(result) == "object"){  fnObj = result;
 } else {
 fnObj = obj;
 }
 
 | 
// 实现:
| 12
 3
 4
 5
 6
 7
 8
 9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 
 | function objectFactory() {let newObject = null,
 constructor = Array.prototype.shift.call(arguments),
 result = null;
 
 
 if (typeof constructor !== "function") {
 console.error("type error");
 return;
 }
 
 
 newObject = Object.create(constructor.prototype);
 
 
 result = constructor.apply(newObject, arguments);
 
 
 let flag =
 result && (typeof result === "object" || typeof result === "function");
 
 
 return flag ? result : newObject;
 }
 
 
 
 
 
 |