function _new(constructer, ...arg) {
// 创建一个空的对象
let resultObj = {};
// 链接该对象到原型,这样新对象就能访问到原型上面的方法
resultObj.__proto__ = constructer.prototype;
// 然后实现步骤3,将新创建的对象作为this的上下文
let result = constructer.call(resultObj, ...arg);
// 实现步骤4:如果该函数没有返回对象(即result不是一个对象),则返回this(即resultObj)
return typeOf result === 'object' ? result : resultobj
// 接下来就可以看看new的实现效果了
}
function Persion(name, age) {
this.name = name;
this.age = age;
}
let Persion1 = _new(Persion, 'lucy', '18');
let Persion2 = _new(Persion, 'chuan', '20');
console.log(Persion1.name); // 'lucy'
console.log(Persion1.name); // 'chuan'
console.log(Persion1 instanceof Persion); // true
console.log(Persion2 instanceof Persion); // true
————————————————
原文链接:https://blog.csdn.net/CallMeBY/article/details/111354627
实现一个new
最新推荐文章于 2024-03-27 10:59:53 发布