本文最后更新于 2024-03-23T16:32:41+00:00
前置知识: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
const obj = {}
obj.__proto__ = constructorFn.prototype
const bindFn = constructorFn.bind(obj)
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)
|