JavaScript new 操作符具体干了什么呢?如何实现?

JavaScript new 操作符具体干了什么呢?如何实现?


new 操作符具体干了什么?

// (1)首先创建了一个新的空对象
// (2)设置原型,将对象的原型设置为函数的 prototype 对象。
// (3)让函数的 this 指向这个对象,执行构造函数的代码(为这个新对象添加属性)
// (4)判断函数的返回值类型,如果是值类型,返回创建的对象。如果是引用类型,就返回这个引用类型的对象。

new共经历了四个过程。

1
2
3
var fn = function () { };
var fnObj = new fn();

1、创建了一个空对象

1
var obj = new object();

2、设置原型链

1
obj._proto_ = fn.prototype;

3、让fn的this指向obj,并执行fn的函数体

1
var result = fn.call(obj);

4、判断fn的返回值类型,如果是值类型,返回obj。如果是引用类型,就返回这个引用类型的对象。

1
2
3
4
5
if (typeof(result) == "object"){  
fnObj = result;
} else {
fnObj = obj;
}

// 实现:

1
2
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;
}

// 新建一个空对象,对象的原型为构造函数的 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(构造函数, 初始化参数);