以下为ChatGPT自动生成的解答,正确与否请自行判断。
BFE.devAI解答 - JavaScript 代码题
53. 用es5实现`extends`
解题思路:
- 创建一个新函数,使用 superType 构造函数初始化 this
- 设置新函数的 prototype 为 superType.prototype
- 将 SubType.prototype 继承到新函数的 prototype 上,确保新函数拥有 SubType 的方法和属性
- 将 constructor 设为 SubType,确保可以通过 new 调用 SubType 的 constructor
具体代码实现如下:
function myExtends(superType, subtype) {
function newType() {
superType.apply(this, arguments);
subtype.apply(this, arguments);
}
Object.setPrototypeOf(newType.prototype, superType.prototype);
Object.getOwnPropertyNames(subtype.prototype).forEach((prop) => {
newType.prototype[prop] = subtype.prototype[prop];
});
newType.prototype.constructor = subtype;
return newType;
}
测试代码:
const InheritedSubType = myExtends(SuperType, SubType);
const instance = new InheritedSubType('test');
console.log(instance.name); // test
console.log(instance.from); // sub
console.log(instance.forSuper); // [1, 2]
console.log(instance.forSub); // [3, 4]
instance.method(); // SubType method
instance.subMethod(); // SubType subMethod
instance.superMethod(); // SuperType superMethod
console.log(InheritedSubType.staticSuper); // staticSuper
console.log(InheritedSubType.staticSub); // undefined