类相关
/**
* 手写new
* @param {*} fn 构造函数
* @param {...any} args 参数
* @returns 对象
*/
function myNew(fn, ...args) {
let obj = {};
Object.setPrototypeOf(obj, fn.prototype);
fn.apply(obj, args);
return obj;
}
instanceof
/**
* 手撕instanceof
* @param {*} obj 对象
* @param {*} clazz 类
* @returns 是否为clazz的实例
*/
function myInstanceof(obj, clazz) {
let proto = Object.getPrototypeOf(obj);
while (proto !== null) {
if (proto === clazz.prototype) {
return true;
} else {
proto = Object.getPrototypeOf(proto);
}
}
return false;
}
继承
原型链继承
/**
* 原型链继承
* 缺点:两个实例使用的是同一个原型对象,内存空间是共享的,在一个对象上修改父类原型上的数据,其他继承同一个父类的对象也会被改变
* @param {*} Child 子类构造函数
* @param {*} Parent 父类构造函数
*/
function myExtends1(Child, Parent) {
Child.prototype = new Parent();
Child.prototype.constructor = Child;
}
构造函数继承
/**
* 构造函数继承
* 缺点:无法继承原型上的属性和方法
* @param {*} Child 子类构造函数
* @param {*} Parent 父类构造函数
*/
function myExtends2(Child, Parent) {
return function (...args) {
Parent.call(this, ...args);
Child.apply(this, args);
};
}
组合继承
/**
* 组合继承
* 缺点:父类构造函数执行了两次
* @param {*} Child 子类构造函数
* @param {*} Parent 父类构造函数
*/
function myExtends3(Child, Parent) {
function TemplateChild(...args) {
Parent.call(this, ...args);
Child.apply(this, args);
}
TemplateChild.prototype = new Parent();
TemplateChild.prototype.constructor = Child;
return TemplateChild;
}
原型式继承
/**
* 原型式继承
* 缺点:因为是浅拷贝原型对象属性是共享的,多个实例会引用同一个原型对象
* @param {*} obj 原型对象
* @returns 新对象
*/
function myExtends4(obj) {
return Object.create(obj);
}
寄生式继承
/**
* 寄生式继承
* 缺点:因为是浅拷贝原型对象属性是共享的,多个实例会引用同一个原型对象
* @param {*} obj 原型对象
* @returns 新对象
*/
function myExtends5(obj) {
const clone = Object.create(obj);
// 增加自己需要的方法
clone.say = function () {
console.log("Say");
};
return clone;
}
寄生组合式继承
/**
* 寄生组合式继承
* 缺点:因为是浅拷贝原型对象属性是共享的,多个实例会引用同一个原型对象
* @param {*} Child 子类构造函数
* @param {*} Parent 父类构造函数
*/
function myExtends6(Child, Parent) {
function TemplateChild(...args) {
Parent.call(this, ...args);
Child.apply(this, args);
}
TemplateChild.prototype = Object.create(Parent.prototype);
TemplateChild.prototype.constructor = Child;
return TemplateChild;
}
贡献者
版权所有
版权归属:wynnsimon