js常见的继承方式
1. 原型链继承
function Parent1() {
this.name = 'parent1';
this.play = [1,2,3];
}
function Child1() {
this.type = 'child2'
}
Child1.prototype = new Parent1()
const child1 = new Child1();
const child2 = new Child1();
child1.play.push(3)
2. 构造函数继承
function Parent1() {
this.name = 'parent1'
}
Parent1.prototype.getName = function() {
return this.name
}
function Child1() {
Parent1.call(this)
this.type = 'child1'
}
const child1 = new Child1()
console.log(child1);
console.log(child1.getName);
3. 组合式继承
function Parent1() {
this.name = 'parent1';
this.type = [1,2,3]
}
Parent1.prototype.say = function() {
return this.attr
}
function Child1() {
// 第二次执行
Parent1.call(this)
this.attr = 'child1';
}
// 第一次执行
Child1.prototype = new Parent1();
/* 修改构造函数指向 */
Child1.prototype.constructor = Child1;
const child1 = new Child1();
const child2 = new Child1();
child1.type.push(1)
console.log(child1);
console.log(child2);
console.log(child1.say());
console.log(child2.say());
4. 原型式继承
const Parent1 = {
name: '张三',
list: [1,2,3],
getName: function() {
return this.name
}
}
const child1 = Object.create(Parent1)
const child2 = Object.create(Parent1)
child1.list.push(1)
child1.name = '亚索'
console.log(child1.name);
console.log(child1.getName());
console.log(child2.name);
console.log(child1.list);
console.log(child2.list);
5. 寄生式继承
const Parent1 = {
name: '张三',
list: [1,2,3],
getName: function() {
return this.name
}
}
function clone(parent) {
const clone = Object.create(parent)
clone.getList = function() {
return this.list
}
return clone
}
const child1 = clone(Parent1)
const child2 = clone(Parent1)
child1.name = 'child1'
console.log(child1.name);
console.log(child2.name);
console.log(child1.getName());
console.log(child2.getName());
console.log(child1.getList());
/*********************传统寄生式继承************************/
// 设置父类自有属性和方法
let parent2 = {
name: 'zy',
hobbies: ['tennis', 'music', 'photography'],
getName: function () { console.log(this.name) }
}
// 这个方法用于创建一个新对象并且连接原型链
function object(obj) {
function F() { }
F.prototype = obj;
return new F();
}
function createson(o, sex) {
// 传入父类创建个新对象
let newson = object(o)
// 这里增强对象,添加属性和方法
newson.sex = sex
newson.getsex = function () { console.log(this.sex) }
// 返回对象
return newson
}
let sub2 = createson(parent2, 'famle')
console.log(sub2)
sub2.getName()
sub2.getsex()
6. 寄生组合式继承
function Parent1() {
this.name = 'Parent1',
this.list = [1,2,3]
}
Parent1.prototype.getList = function() {
return this.list
}
function Child1() {
Parent1.call(this)
}
Child1.prototype = Object.create(Parent1.prototype);
Child1.prototype.construct = Child1
const child1 = new Child1()
const child2 = new Child1()
const child3 = new Child1()
child1.list.push(1)
child1.name = 'child1'
console.log(child1.name);
console.log(child2.name);
console.log(child1.getList());
console.log(child2.getList());