new 操作符实现

119 阅读1分钟

new 操作符干了啥?

1、创建一个空对象

2、把对象的原型指向构造函数的prototype

3、把创建的对象作为构造函数的上下文(改变this的指向)

4、对执行构造函数有无返回值的处理:

1)、返回的是基本类型那就直接返回创建的对象

2)、返回的引用类型直接返回

实现自己的 new 函数

`function Parent (name, age) {
   this.name = name;
   this.age = age;
 };
 const child = new Parent('你好', 24); // {name = '你好', age: 24}`
`function myNew(fn, ...args){
   let obj = {};
   obj.__proto__ = fn.prototype;
   let res = fn.apply(fn, args);
   return res instanceof Object ? res : obj;
}
const myNewRes = myNew(Parent, 'myNew', 10)
console.log(myNewRes.name) // myNew
console.log(myNewRes.age) // 10`

function myNew2() {
   let obj = new Object()
   let fn = [].shift.call(arguments);
   obj.__proto__ = fn.prototype;
   let res = fn.apply(obj,arguments);
   return res instanceof Object ? res : obj;
}
const myNewRes = myNew2(Parent, 'myNew2', 20)
console.log(myNewRes.name) // myNew2
console.log(myNewRes.age) // 20`