每天做个总结吧,坚持就是胜利!
/**
@date 2021-05-24
@description new一个函数时发生了什么?
*/
壹(序)
new运算符用于构建一个用户自定义函数的实例,或js内置的带有构造函数的对象实例。
贰(步骤)
- 创建一个新的空对象;
- 使该新对象的[[prototype]]指向构造函数的prototype;
- 绑定this到新对象中;
- 如果构造函数返回一个对象,则返回该对象,否则返回新创建的对象;
叁(实现)
function newOperator(ctor, ...args) {
// 创建一个新对象,并将该对象的[[prototype]]指向构造函数的prototype
const obj = Object.create(ctor.prototype);
// 绑定this到新对象中
const res = ctor.apply(obj, args);
// 判断构造函数返回的是否是一个对象,是则返回,否则返回新创建的对象
const resType = typeof res;
return (resType === 'object' && resType !== null) || resType === 'function'
? res
: obj;
}
function Test() {
this.a = 1;
this.b = 2;
}
console.log(newOperator(Test)); // Test {a: 1, b: 2}
肆(引申)
实现原型继承:
// 创建父类
function Parent() {
this.name = 'parent';
}
// 创建子类
function Child() {
// 子类调用父类
Parent.apply(this);
// 定义子类自身属性
this.age = 18;
}
// 子类prototype指向父类prototype
Child.prototype = Object.create(Parent.prototype);
// 重建子类的constructor(指向子类自身)
Child.prototype.constructor = Child;
console.log(new Child('test', 18)); // Child {name: 'parent', age: 18}