残缺高频题库仓库地址:https://github.com/hzfe/awesome-interview
残缺高频题库浏览地址:https://febook.hzfe.org/
相干问题
- new 操作符做了什么
- new 操作符的模仿实现
答复关键点
构造函数
对象实例
new 操作符通过执行自定义构造函数或内置对象构造函数,生成对应的对象实例。
知识点深刻
1. new 操作符做了什么
- 在内存中创立一个新对象。
- 将新对象外部的 \_\_proto\_\_ 赋值为构造函数的 prototype 属性。
- 将构造函数外部的 this 被赋值为新对象(即 this 指向新对象)。
- 执行构造函数外部的代码(给新对象增加属性)。
- 如果构造函数返回非空对象,则返回该对象。否则返回 this。
2. new 操作符的模仿实现
function fakeNew() { // 创立新对象 var obj = Object.create(null); var Constructor = [].shift.call(arguments); // 将对象的 __proto__ 赋值为构造函数的 prototype 属性 obj.__proto__ = Constructor.prototype; // 将构造函数外部的 this 赋值为新对象 var ret = Constructor.apply(obj, arguments); // 返回新对象 return typeof ret === "object" && ret !== null ? ret : obj;}function Group(name, member) { this.name = name; this.member = member;}var group = fakeNew(Group, "hzfe", 17);
参考资料
- new 操作符 - MDN
- The new Operator