当我们经常用new ClassName()的时候,new做了哪些事情呢?
- 首先创建一个空对象o
- 给o设置__proto__属性并指向给ClassName.prototype
- 设置o的constructor为ClassName
- 用o修改this指向的方式调用函数
- 将初始化完的对象0返回
// 实现原生new的方式
function myNew(className, ...arg) {
// 1、创建一个空对象
let o = {} // 相当于执行:Object.create(Object.prototype)
// 2、给o对象设置__proto__属性并指向给className.prototype对象
o.__proto__ = className.prototype
// 3、设置o的constructor为className
o.constructor = className.prototype.constructor
// 4、使用o调用函数,通过call改变this指向
const result = className.apply(o, arg)
// 5、//当无返回对象或默认时返回新创建的对象o。
return typeof result === 'object' && result != null ? result : o;
}
function Persion(name, age) {
// 实例自身就有下面的属性、方法
this.name = name
this.age = age
this.sayName = function () {
console.log(this.name)
}
}
// 实例的sayAge是通过prototype获取到的
Persion.prototype.sayAge = function () {
console.log(this.age)
}
// const zhangsan = new Persion('张三', 25)
const zhangsan = myNew(Persion, '张三', 25)
console.log('Persion.prototype', Persion.prototype)
console.log('constructor', Persion === zhangsan.constructor)
console.log(111, zhangsan)
console.log(Persion.prototype.isPrototypeOf(zhangsan))