function Person(name, age){
this.name = name;
this.age = age;
}
let person = new Person("halou", 18);
console.log(person); // Person {name: "halou", age: 18}
2.手写new
function new2(fn, ...args) {
// 1. 判断是否是函数
if (typeof fn !== 'function') {
throw '第一个参数必须是函数';
}
// 2. 创建新对象
const obj = {};
// 3. 这个对象的 __proto__ 指向 fn 这个类的原型对象
// 即实例可以访问构造函数原型(constructor.prototype)所在原型链上的属性
obj.__proto__ = fn.prototype;
// 4. 通过 apply 绑定 this 执行并且获取运行后的结果
let res = fn.apply(obj, args);
// 5. 如果构造函数返回的结果是引用数据类型,则返回运行后的结果
// 否则返回新创建的 obj
const isObject = typeof res === 'object' && typeof res !== null;
const isFunction = typeof res === 'function';
return isObject || isFunction ? res : obj;
}