JS中的new 的关键底层机制:new到底干了啥?
const 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
参考:
原文:https://www.cnblogs.com/rookie123/p/14278116.html