定义
new 运算符创建一个用户定义的对象类型的实例或具有构造函数的内置对象的实例。 (MDN)
操作
- 创建一个空的简单JavaScript对象(即{});
- 链接该对象(即设置该对象的构造函数)到另一个对象 ;
- 将步骤1新创建的对象作为this的上下文 ;
- 如果该函数没有返回对象,则返回this。
语法
Object = new constructor([argument])
模拟实现
/**
* 模仿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 {}
可以看到 返回结果结构一致 同时Constructor和原型也一致
原文:《描述new一个对象的详细过程以及手动实现一个new操作符》
ps:文末附上汇总文章链接《一名【合格】前端工程师的自检清单【自检ing】》