1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* 实现 new 基本原理*/
function myNew() {
let obj = {}
let Con = [].shift.call(arguments)
obj.__proto__ = Con.prototype
let res = Con.apply(obj, arguments)
return res instanceof Object ? res : obj
}
/* 以下是对实现的分析:
- 创建⼀个空对象
- 获取构造函数
- 设置空对象的原型
- 绑定 this 并执⾏构造函数
- 确保返回值为对象 */

1
2
3
4
function myNew(obj, ...args) {
let newObj = Object.create(obj.prototype)
let result = obj.apply(newObj, args)
}