工欲善其事必先利其器,我们要想实现new关键字,我们要知道new关键字是干嘛用的,原理是什么?来来来我们一起来看一看...
new 干了些什么
我们在使用new 创建对象的时候他会帮我们做以下四件事情:
1. 帮我们创建一个空对象;
2. 将新对象的原型(prototype)指向构造函数的原型(prototype);
3. 执行构造函数,把构造函数的属性添加到新对象;
4. 返回创建的新对象;
实现一个new
function _new(func, ...rest) {
// 创建空对象,并将新对象的__proto__属性指向构造函数的prototype
const obj = Object.create(func.prototype)
// 执行构造函数,改变构造函数的this指针,指向新创建的对象(新对象也就有了构造函数的所有属性)
func.apply(obj, rest)
return obj
}
验证 _new
function _new(func, ...rest) {
// 创建空对象,并将新对象的__proto__属性指向构造函数的prototype
const obj = Object.create(func.prototype)
// 执行构造函数,改变构造函数的this指针,指向新创建的对象(新对象也就有了构造函数的所有属性)
func.apply(obj, rest)
return obj
}
function People() {
this.name = 'paopao'
this.age = 3
}
const p = _new(People)
console.log(JSON.stringify(p))
// "{"name":"paopao","age":3}"
console.log(p.__proto__ === People.prototype)
// true
console.log(p.name)
// "paopao"
console.log(p.constructor === People)
// true