导读
了解js中new的原理,你要先知道arguments
和apply
后续会另外讲解下bind,call,apply
过程
- 我们需要知道当 new 的时候做了什么事情
- 创建一个新对象;
- 将构造函数的作用域赋给新对象(因此 this 就指向了这个新对象)
- 执行构造函数中的代码(为这个新对象添加属性)
- 返回新对象。
function New() {
// Constructor 表示 new 的构造器
const Constructor = Array.prototype.shift.call(arguments)
// new 的对象不是函数就抛 TypeError
if (typeof Constructor !== 'function') throw new TypeError(`${Constructor} is not a Constructor`);
// 创建一个原型为构造器的 prototype 的空对象 target
const target = Object.create(Constructor.prototype);
// 将构造器的 this 指向上一步创建的空对象,并执行,为了给 this 添加实例属性
const result = Constructor.apply(target, arguments);
// 上一步的返回如果是对象就直接返回,否则返回 target
return isObject(result) ? result : target;
}
// 简单区分函数与对象
function isObject(value) {
const type = typeof value;
return value !== null && (type === 'object' || type === 'function');
}
// 构造函数 - Computer
function Computer(brand) {
this.brand = brand;
}
// 实例对象 - kevin
const kevin = New(Computer, 'kevin');
console.log(kevin); // => Computer { brand: 'kevin' }
console.log(kevin instanceof Computer); // true
小结
希望看完本篇文章能对你有如下帮助:
- 了解构造函数 new 的过程
文中如有错误,欢迎在评论区指正,如果这篇文章帮助到了你,欢迎点赞和关注。