模拟new
tip
考察类继承
、this
指针、原型链
的知识点
一、题意
实现代码中的myNew
方法, 使输出结果与程序中一致。
function Leon(name, age) {
this.name = name;
this.age = age;
this.habit = 'Games';
}
Leon.prototype.strength = 60;
Leon.prototype.sayYourName = function () {
console.log('I am ' + this.name);
}
// 调用myNew,实现继承
const person = myNew(Leon, 'leon', '27');
console.log(person.name); // leon
console.log(person.habit); // Games
console.log(person.strength);// 60
person.sayYourName(); // I am leon
二、解法
// 参数fn对应的是要继承的类Leon的构造函数
function myNew(fn, ...args){
// 依据原型链,创建新的对象,使新对象obj,继承原型链上的属性和方法
const obj = Object.create(fn.prototype);
// 执行构造函数fn,并改变fn的this指针,指向obj
// 此种调用方式,称为泛型方法调用
const ret = fn.apply(obj, args);
// ret有可能为null,需要进行判断,保证链式调用的可用性
return typeof ret === 'object' ? ret || obj : obj;
}