new 的过程都干了什么

new的过程

- 新生成一个对象
- 链接到原型(继承该函数的原型)
- 绑定this(将原型中的属性和方法加入到this引用的对象中)
- 返回新对象

自己实现一个new:

1
2
3
4
5
6
7
8
9
10
11
12
function create() {
// 创建一个空的对象
let obj = new Object()
// 获得构造函数
let Con = [].shift.call(arguments)
// 设置新对象的__proto__属性指向构造函数的prototype属性
obj.__proto__ = Con.prototype
// 绑定 this,函数中this指向新实例对象。
let result = Con.apply(obj, arguments)
// 确保 new 出来的是个对象
return typeof result === 'object' ? result : obj
}

// 简洁版的new实现过程

1
2
3
4
5
6
7
8
9
10
function newFunc(constructor){
//第一步:创建一个空对象obj
var obj = {};
//第二步:将构造函数 constructor的原型对象赋给obj的原型
obj.__proto__ = constructor.prototype;
//第三步:将构造函数 constructor中的this指向obj,并立即执行构造函数内部的操作
constructor.apply(obj);
//第四步:返回这个对象
return obj;
}

原文:大专栏  new 的过程都干了什么


猜你喜欢

转载自www.cnblogs.com/wangziqiang123/p/11652412.html