FE-Interview
FE-Interview copied to clipboard
new 的实现原理,动手实现一个 new
扫描下方二维码,获取答案以及详细解析,同时可解锁800+道前端面试题。
- 创建一个全新的对象
- 执行 prototype 链接
- 绑定到函数调用的this
- 如果没有返回对象则返回new出来的对象
const myNew = (constructor, ...args) => {
const obj = {};
Object.setPrototypeOf(obj, constructor.prototype);
const result = constructor.call(obj, ...args);
return result instanceof Object ? result : obj;
}
Function.prototype.mynew=function(func,...args) {
let obj={}
//新对象 连接
obj.__proto__=func.prototype
let re=func.apply(obj,args)
return re instanceof Object?re:obj
}
// 定义一个构造函数
function Person(name, age) {
this.name = name;
this.age = age;
}
// 使用 mynew 创建一个新对象
const john = Person.mynew(Person, 'John', 30);
console.log(john.name); // 输出: John