当前位置:网站首页>了解一下new的过程发生了什么
了解一下new的过程发生了什么
2022-07-25 15:00:00 【Henry_楠】
之前看过相关文章,结果时间一久又忘了,果然还是得撸一篇文章才行
一、了解new
先看一下mdn对 new 的介绍: new 运算符
new会进行以下操作:
- 创建一个空的简单JavaScript对象(即{}),称之为A;
- 链接该对象A的构造函数(设置对象A的constructor)到另一个对象(即你要new的那个构造函数) ;
- 将步骤1新创建的对象A作为this的上下文 ;
- 如果该函数没有返回对象,则返回this。
二、模拟一个new的过程
废话不多说,直接上代码:
function _new(constructor,...arg){
const obj = {
}
obj.__proto__ = constructor.protoType
const res = constructor.apply(obj,arg)
return res instanceof Object ? res : obj
}
function User(name){
this.name = name
}
function User1(name){
this.name = name
return {
}
}
console.log(_new(User, 'henry')); //{ name: 'henry' }
console.log(new User('henry')); //{ name: 'henry' }
console.log(_new(User1, 'henry'));//{}
console.log(new User1('henry')); //{}
注意箭头函数不能当构造函数,不能被new,具体的可以参考 MDN
下一篇介绍一下 继承,继承的实现过程及ES5和ES6实现的区别
边栏推荐
- [Android] recyclerview caching mechanism, is it really difficult to understand? What level of cache is it?
- QT connect, signal, slot and lambda comparison
- Browser based split screen reading
- [C题目]力扣206. 反转链表
- PHP 通过原生CURL实现非阻塞(并发)请求模式
- 41 图片背景综合-五彩导航图
- C, c/s upgrade update
- "How to use" agent mode
- Reprint ---- how to read the code?
- Fast-lio: fast and robust laser inertial odometer based on tightly coupled IEKF
猜你喜欢

Overview of cloud security technology development

Deng Qinglin, a technical expert of Alibaba cloud: Best Practices for disaster recovery and remote multi activity across availability zones on cloud

pl/sql 创建并执行oralce存储过程,并返回结果集

IP address classification, which determines whether a network segment is a subnet supernetwork

"Ask every day" reentrantlock locks and unlocks

Nacos2.1.0 cluster construction

"Ask every day" briefly talk about JMM / talk about your understanding of JMM

The solution to the problem that the progress bar of ros2 installation connext RMW is stuck at 13%

String type time comparison method with error string.compareto

39 simple version of millet sidebar exercise
随机推荐
27 选择器的分类
Share a department design method that avoids recursion
45padding不会撑开盒子的情况
35 quick format code
MFC 线程AfxBeginThread基本用法,传多个参数
"Ask every day" reentrantlock locks and unlocks
ESXI6.7.0 升级到7.0U3f(2022年7月12 更新)
"Ask every day" briefly talk about JMM / talk about your understanding of JMM
Heyuan City launched fire safety themed milk tea to boost fire prevention and control in summer
Splice a field of the list set into a single string
easygui使用的语法总结
bridge-nf-call-ip6tables is an unknown key异常处理
[C题目]力扣206. 反转链表
Resource not found: rgbd_ Launch solution
[C topic] force buckle 876. Intermediate node of linked list
深入:微任务与宏任务
[Nuxt 3] (十一) 传送 & 模块
Deng Qinglin, a technical expert of Alibaba cloud: Best Practices for disaster recovery and remote multi activity across availability zones on cloud
MySQL sort
Install entityframework method