js实现继承的方法总结
该篇仅总结了其中三个方法并分析了其优缺点,其余方法可自行学习。
方法一:原型链实现继承
function Parent2() {
this.name = 'parent2';
this.play = [1, 2, 3];
this.say = () => {
console.log('say');
}
}
Parent2.prototype.age = [];
function Child2() {
this.type = 'child2';
}
Child2.prototype = new Parent2();
console.log(new Child2().type);
console.log(new Child2().name);
console.log(new Child2().play);
var s1 = new Child2();
var s2 = new Child2();
s1.play.push(4);
console.log(s1.play);
console.log(s2.play);
s1.say();
方法二:构造函数实现继承
function Parent1() {
this.name = 'parent1';
}
Parent1.prototype.say = function () {
console.log('say');
}
Parent1.prototype.family = [1, 2, 3];
function Child1() {
Parent1.call(this);
this.type = 'child1';
}
console.log(new Child1().name);
console.log(new Child1().say);
console.log(new Child1().family);
方法三:组合模式
function Person3(x) {
this.name = x;
this.arr = [];
}
Person3.prototype.say = function () {
console.log('say');
}
function Child3(x) {
this.nickName = 'child3' + x;
Person3.call(this, x);
}
Child3.prototype = new Person3();
const c1 = new Child3('zhoul');
c1.arr.push(1)
const c2 = new Child3('lan');
console.log(c1.name, c2.name, c1.arr, c2.arr, c1.nickName);
c1.say();
- 优化父类的构造方法被执行了2次:(寄生组合继承)
