手写原理 | new操作符

MDN

new运算符创建一个用户定义的对象类型的实例或者具有构造函数的内置对象的实例

语法

1
new constructor[([arguments])]

参数

constructor:一个指定对象实例的类型的类或函数

arguments:一个用于被constructor调用的参数列表

手写new

new关键字会进行如下操作

  1. 创建一个空对象
  2. 为空对象添加__proto__,指向构造函数的prototype对象
  3. 将新对象作为this的上下文,并且执行构造函数内部的代码(给新对象添加属性)
  4. 如果该函数没有返回对象,则返回this

对于返回值的说明

  • 如果构造函数有返回值且是对象,则返回这个对象
  • 如果构造函数有返回值且不是对象,则返回创建的空对象
  • 如果构造函数没有返回值,返回创建的空对象

手写new

1
2
3
4
5
6
7
8
function myNew() {
let newObj = {};
let constr = Array.prototype.shift.call([...arguments]);
let proto = constr.prototype;
newObj = Object.create(proto);
let res = constr.apply(newObj, [...arguments]);
return typeof res === 'object' ? res : newObj;
};

测试

1
2
3
4
5
6
7
8
function Person(name, age) {
this.name = name;
this.age = age;
};

let person = myNew(Person, 'Katrina', 18);
console.log(person); // {name: 'Katrina', age: 18}
console.log(person instanceof Person); // true

知识补充

手写instanceof

手写Object.create