new 关键字会进行如下的操作:
- 创建一个空的简单JavaScript对象(即
{}); - 为步骤1新创建的对象添加属性
__proto__,将该属性链接至构造函数的原型对象 ; - 将步骤1新创建的对象作为
this的上下文 ; - 如果该函数没有返回对象,则返回
this。 简记: - 创(创建对象)
- 链(链接至constructor的原型对象)
- 指(this指向创建的对象)
- 返(返回对象或this)
按照四步骤模拟实现 new,来自原文
/**
* 模仿new关键词实现
* @param {Function} constructor 构造函数
* @param {...any} argument 任意参数
*/
const _new = (constructor,...argument) => {
const obj = {} //创建一个空的简单对象
obj.__proto__ = constructor.prototype //设置原型
const res = constructor.apply(obj, argument) //新创建的对象作为this的上下文传递给构造函数
return (typeof res === 'object') ? res : obj //如果该函数没有返回对象,则返回this(这个this指constructor执行时内部的this,即res))。
}
function Person(name,sex){
this.name = name
this.sex = sex
}
const people = new Person('Ben','man');
const peopleOther = _new(Person,'Alice','woman');
console.info('people',people);// people Person { name: 'Ben', sex: 'man' }
console.info('peopleOther',peopleOther);// peopleOther Person { name: 'Alice', sex: 'woman' }
console.info('people.__proto__',people.__proto__);//people.__proto__ Person {}
console.info('peopleOther.__proto__',peopleOther.__proto__);//peopleOther.__proto__ Person {}