手写new方法原创
# 手写new方法
// 创建对象,并将对象的原型指向构造函数的原型
// 使用新对象调用构造函数
// 调用结果返回值是一个对象,则直接返回,否则返回新创建的对象。
Function.prototype.myNew = function(...args){
let obj = Object.create(this.prototype);
let res = this.apply(obj,args);
return typeof res === "object"?res:obj;
}
1
2
3
4
5
6
7
8
2
3
4
5
6
7
8