new 操作符做了什么
new 操作符的模拟实现
构造函数 对象实例
new 操作符通过执行自定义构造函数或内置对象构造函数,生成对应的对象实例。
在内存中创建一个新对象。
将新对象内部的 proto 赋值为构造函数的 prototype 属性。
将构造函数内部的 this 被赋值为新对象(即 this 指向新对象)。
执行构造函数内部的代码(给新对象添加属性)。
如果构造函数返回非空对象,则返回该对象。否则返回 this。
1function fakeNew() {
2 // 创建新对象
3 var obj = Object.create(null);
4 var Constructor = [].shift.call(arguments);
5 // 将对象的 __proto__ 赋值为构造函数的 prototype 属性
6 obj.__proto__ = Constructor.prototype;
7 // 将构造函数内部的 this 赋值为新对象
8 var ret = Constructor.apply(obj, arguments);
9 // 返回新对象
10 return typeof ret === "object" && ret !== null ? ret : obj;
11}
12
13function Group(name, member) {
14 this.name = name;
15 this.member = member;
16}
17
18var group = fakeNew(Group, "hzfe", 17);