new的实现原理
• 以构造器的prototype属性为原型,创建新对象;
• 将this(也就是上一句中的新对象)和调用参数传给构造器,执行;
• 如果构造器没有手动返回对象,则返回第一步创建的新对象,如果有,则舍弃掉第一步创建的新对象,返回手动return的对象。
实现new方法
- 定义一个构造器函数
// 构造器函数
let Parent = function(name, age) {
this.name = name;
this.age = age;
};
Parent.prototype.sayName = function() {
console.log(this.name);
};
- 实现new方法
- 1.创建一个空对象
- 2.链接到原型
- 3.绑定this值
- 4.返回新对象
//定义的new方法
let newMethod = function(Parent, ...rest) {
// 1.以构造器的prototype属性为原型,创建新对象(1、2);
let newObj = Object.create(Parent.prototype);
// 2.将this和调用参数传给构造器执行(3)
let result = Parent.apply(newObj, rest);
// 3.如果构造器没有手动返回对象,则返回第一步的对象(4)
return typeof result === 'object' ? result : newObj;
};
- 调用函数,创建新对象
//创建实例,将构造函数Parent与形参作为参数传入
const child = newMethod(Parent, 'echo', 26);
child.sayName() //'echo';