8、手写 new

前置知识:15、new 干了什么事情? - 掘金
由于new是关键词,所以我们手写时将其绑到Function.prototype上,方便使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
Function.prototype.New = function(...args) {
// 构造函数
const constructorFn = this

// 1、创建一个空对象
const obj = {}

// 2、将该空对象的__proto__指向构造函数的 prototype
obj.__proto__ = constructorFn.prototype

// 3、将 this 指向该空对象
const bindFn = constructorFn.bind(obj)

// 4、执行构造函数
const result = bindFn(...args)

if(typeof result === 'obj') return result
else return obj
}

// 具体使用:
function Person(name, age) {
this.name = name
this.age = age
}

const p1 = Person.New('张三', 35) // { name: '张三', age: 35 }

// p1 instanceof Person 为 true

8、手写 new
https://mrhzq.github.io/职业上一二事/前端面试/每日一题/8、手写 new/
作者
黄智强
发布于
2024年1月23日
许可协议