手写new运算符
首先来看看new在执行的过程中都做了什么
- 首先创建一个空对象
- 继承父类的prototype
- 将this指向第一步新创建的的对象
- 判断该函数是否存在返回值,如果没有就将this返回
- 先来看看原本的new输出的结果是什么样的
function Person(name, age) {
this.name = name
this.age = age
}
let b = new Person('哈哈哈', 12)
console.log(b)
- 下面就按照步骤来手写一下new运算符吧
function myNew(obj, ...args) {
// const newObj = {}
// newObj.__proto__=obj.prototype
//以上两步可以简化为一步,直接创建一个以obj.prototype为原型的对象
const newObj = Object.create(obj.prototype)
const result = obj.apply(newObj, args)
return result instanceof Object ? result : newObj
}
// 来试试手写的结果
function Person(name, age) {
this.name = name
this.age = age
}
let p = myNew(Person, '哈哈哈', 12)
console.log(p)