new操作符的执行过程
- 首先创建了一个新的空对象;我们将传入的参数对象arguments利用Array.from()转化为数组。利用shift()弹出数组的第一个元素,也就是传入的构造函数,并保存到了变量constructor里。
- 设置原型;将空对象的隐式原型设置为构造函数的 prototype 对象。
- 让函数的 this 指向这个新创建的空对象,并调用函数得到返回值。
- 判断返回值类型,如果是基本数据类型,则返回我们创建的对象。如果是引用类型,就返回这个引用类型的对象。
function _new(){
//1.创建了一个空对象
let newObj = null;
let arr = Array.from(arguments); //将参数转化为数组
let constructor = arr.shift(); //得到第一个参数:构造函数
//2.将newObj的原型设置为constructor的prototype对象
newObj = newObj.create(constructor.prototype);
//3.将constructor的this指向newObj,并执行函数
let result = constructor.apply(newObj, arr);
//4.判断返回值类型
if (result instanceof Object) {
//如果是,则返回该函数的返回值
return result;
} else {
//如果不是就返回newObj
return newObj;
}
}
function Person(name,age) {
this.name = name;
this.age = age;
}
Person.prototype.say = function () {
console.log(`我叫${this.name},今年${this.age}岁`);
}
const test = _new(add,'小陈',23);
console.log(test); // Person {name: '小陈', age: 23}
test.say(); //我叫小陈,今年23岁