New|New 操作符的原理
完整高频题库仓库地址:https://github.com/hzfe/awesome-interview
完整高频题库阅读地址:https://febook.hzfe.org/
相关问题
- new 操作符做了什么
- new 操作符的模拟实现
构造函数
对象实例
【New|New 操作符的原理】new 操作符通过执行自定义构造函数或内置对象构造函数,生成对应的对象实例。
知识点深入 1. new 操作符做了什么
- 在内存中创建一个新对象。
- 将新对象内部的 \_\_proto\_\_ 赋值为构造函数的 prototype 属性。
- 将构造函数内部的 this 被赋值为新对象(即 this 指向新对象)。
- 执行构造函数内部的代码(给新对象添加属性)。
- 如果构造函数返回非空对象,则返回该对象。否则返回 this。
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
推荐阅读
- Shell-Bash变量与运算符
- 2.6|2.6 Photoshop操作步骤的撤消和重做 [Ps教程]
- MongoDB,Wondows下免安装版|MongoDB,Wondows下免安装版 (简化版操作)
- 一起来学习C语言的字符串转换函数
- C语言字符函数中的isalnum()和iscntrl()你都知道吗
- 在线版的迅捷思维导图怎么操作()
- 操作系统|[译]从内部了解现代浏览器(1)
- 字符串拼接成段落,换行符(\n)如何只执行n-1次
- 爬虫数据处理HTML转义字符
- 数据库总结语句