手写new操作符
JS中的new 的关键底层机制:new到底干了啥?
- 创建一个空的对象
const obj = {};
- 设置obj._proto_ = Fn.prototype,绑定this到obj上, 执行Fn(构造函数)
- 如果2中的Fn返回的不是引用类型,则返回obj
手写new :可以看到下面的new的实现基本上是按照以上步骤的
function _new(Fn, ...args) {
const obj = {};
obj.__proto__ = Fn.prototype;
let res = Fn.call(obj, ...args);
if ((res !== null) && (typeof res === 'object' || typeof res === 'function')) {
return res;
}
return obj;
}
测试一下
function Dog(name, age) {
this.name = name;
this.age = age;
}
Dog.prototype.sayInfo = function() {
console.log(`Name = ${this.name}, Age = ${this.age}`);
}
let dog = _new(Dog, 'Hello', 12);
dog.sayInfo();s
参考:
- MDN
慢慢来,比较快!基础要牢,根基要稳!向大佬致敬!