ES5模拟ES6class继承
// ES6继承
class Human {
constructor(name) {
this.name = name;
}
}
class Man extends Human {
constructor(args) {
super(args);
}
speak() {
console.log(this.name);
}
}
const jame = new Man("jame");
jame .speak()
// ES5继承
function Human(name) {
this.name = name;
}
function Man(name) {
Human.call(this, name);
}
/**
1. 这一步不用Child.prototype = Parent.prototype的原因是怕共享内存,修改父类原型对象就会影响子类
2. 不用Child.prototype = new Parent()的原因是会调用2次父类的构造方法(另一次是call),会存在一份多余的父类实例属性
3. Object.create是创建了父类原型的副本,与父类原型完全隔离
*/
Man.prototype = Object.create(Human.prototype);
Man.prototype.say = function () {
console.log(this.name);
};
// 构造器指向自身
Man.prototype.contructor = Man;
const chris = new Man("chris");
chris.say();
本文标题:ES5模拟ES6class继承
本文链接:https://www.haomeiwen.com/subject/qgmwxktx.html
网友评论