new 构造函数()执行顺序
- 在堆中开辟对象内存空间, 记为obj
- 在obj 中添加
__proto__
属性并指向 构造函数.prototype
- 将构造函数中的this 指向obj
- 执行构造函数内语句
- 若构造函数中
没有reutrn 或return this或基本类型
(number、string、boolean、null、undefined)的值,则返回obj在堆中的内存地址;若return 引用类型
,则返回值为这个引用类型
仿写new的行为
function People(name, age, phone) {
this.name = name;
this.age = age;
this.phone = phone;
}
function _new(...args) {
let constructor = args[0];
let obj = Object.create(constructor.prototype);
let res = constructor.call(obj, ...args.slice(1));
if ((typeof res === 'object' || typeof res === 'function') && res != null) {
return res;
} else {
return obj;
}
}
let a = _new(People, 'aa', 20, 132456);
let na = new People('aa', 20, 132456);
console.log(a, na);
People { name: 'aa', age: 20, phone: 132456 }
People { name: 'aa', age: 20, phone: 132456 }