参考:
终于懂了原型链!
分析:new操作符的功能
function Person(age) {
this.age = age;
}
let p = new Person(20);
p; // Person {age:20}
- 首先创建了一个空对象
p = {}
__proto__
属性 of p:指向其构造函数 Person 的原型对象prototype
- 构造函数的
this
:绑定到新对象p上面,并执行构造函数 - 若构造函数返回的是非引用类型,则返回该新建的对象 p;否则返回引用类型的值。
手动实现
function Person(name, age) {
this.name = name;
this.age = age;
// 构造函数本身也可能有返回结果
// return {
// name,
// age,
// test:123
// }
}
function _new(Func, ...rest) {
// 1. 定义一个实例对象
let obj = {};
// 2. 手动将实例对象中的__proto__属性指向相应原型对象
// 此时 obj.constructor 就指向了 Person 函数,即 obj 已经承认 Person 函数是它自己的构造函数
obj.__proto__ = Person.prototype;
// 3. obj 需要能够调用构造函数私有属性/方法
// 也就是需要在实例对象的执行环境内调用构造函数,添加构造函数设置的私有属性/方法
let res = Person.apply(obj, rest);
// 4. 如果构造函数内返回的是对象,则直接返回原返回结果(和直接调用函数一样);否则返回新对象。
return res instanceof Object ? res : obj;
}
let p = _new(Person, "张三", "20");
p; // Person{age: "20", name: "张三"}
p.constructor; // ƒ Person() {}