

通过以上几个例子,相信大家也大致了解了 new 操作符的作用了,接下来我们就来尝试自己实现 new 操作符。
自己实现 new 操作符
首先我们再来回顾下 new 操作符的几个作用
回顾了这些作用,我们就可以着手来实现功能了
function create(Con, ...args) {
let obj = {}
Object.setPrototypeOf(obj, Con.prototype)
let result = Con.apply(obj, args)
return result instanceof Object ? result : obj
}这就是一个完整的实现代码,我们通过以下几个步骤实现了它:
接下来我们来使用下该函数,看看行为是否和 new 操作符一致
function Test(name, age) {
this.name = name
this.age = age
}
Test.prototype.sayName = function () {
console.log(this.name)
}
const a = create(Test, 'yck', 26)
console.log(a.name) // 'yck'
console.log(a.age) // 26
a.sayName() // 'yck'虽然实现代码只有寥寥几行,但是结果很完美
最后
我们通过这篇文章重学了 new 操作符,
