原型链继承原理:让子类的原型对象指向父项的实例,当子类找不到爹时候,它会沿着原型链找爷爷。
1:原型链继承展示
function Parent() {
this.name = '你的帅气和胡歌一样'
}
Parent.prototype.getName = function () {
return this.name
}
function Child() {
}
Child.prototype = new Parent()
Child.prototype.constructor = Child
const child = new Child
console.log(child.name);
console.log(child.getName());
2:原型链继承的缺点展示
function Parent() {
this.name = ['你的帅气和胡歌一样']
}
Parent.prototype.getName = function () {
return this.name
}
function Child() {
}
Child.prototype = new Parent()
Child.prototype.constructor = Child
const child1 = new Child
const child2 = new Child
child1.name[0]='彭于晏的胸大肌'
console.log(child1.name);//彭于晏的胸大肌'
console.log(child2.name);//child2没有改,但结果依旧改变了--彭于晏的胸大肌'
2:构造函数继承
无法在原型链继承中 实现supper,--无法实现对父类传参 构造函数可解决原型链继承的缺点,但不能继承父类原型上的方法和属性
所以,老二终究是老二,关键时候还得看我老三
构造函数继承
function Parent(name) {
this.name = [name]
}
Parent.prototype.getName = function () {
return this.name
}
// 在子类的构造函数中,执行父类的构造函数,并且为其绑定子类的this
function Child() {
Parent.call(this, '熊大')
}
const child1 = new Child()
const child2 = new Child()
child1.name[0] = '彭于晏的胸大肌'
console.log(child1.name); //彭于晏的胸大肌'
console.log(child2.name); //熊大
console.log(child2.getName()); //但不能继承父类原型上的方法 和属性
3:最强的组合继承
老三坟头草到腰了,果然我才是苟到最后的
function Parent(name) {
this.name = [name]
}
Parent.prototype.getName = function () {
return this.name
}
function Child() {
Parent.call(this, '熊大')
}
Child.prototype=new Parent()
Child.prototype.constructor=Child
const child1 = new Child()
const child2 = new Child()
child1.name[0] = '彭于晏的胸大肌'
console.log(child1.name); //彭于晏的胸大肌'
console.log(child2.name); //熊大
console.log(child2.getName());//熊大
4:寄生式继承
其实刚才那个有缺点,,寄生式继承一定是最强的!!!
蹬蹬蹬,闪亮登场,最强驾到!!
哼,一群渣渣,最后不还是得我来收拾局面?
function Parent(name) {
this.name = [name]
}
Parent.prototype.getName = function () {
return this.name
}
function Child() {
Parent.call(this, '熊大')
}
// Child.prototype = new Parent()
Child.prototype = Parent.prototype//寄生缺点,子类方法会影响到父类方法
Child.prototype.constructor = Child
const child1 = new Child()
const child2 = new Child()
child1.name[0] = '彭于晏的胸大肌'
console.log(child1.name); //彭于晏的胸大肌'
console.log(child2.name); //熊大
console.log(child2.getName()); //熊大
5:寄生式加浅拷贝
所以寄生式还是有缺点吗?经大佬指点,加了层浅拷贝,正所谓你的就是我的,我的还是我的。(不允许直接改变)
楼上的,你说啥??????你收拾啥??
function Parent(name) {
this.name = [name]
}
Parent.prototype.getName = function () {
return this.name
}
function Child() {
Parent.call(this, '熊大')
}
// Child.prototype = new Parent()
Child.prototype = Object.create(Parent.prototype) //加层浅拷贝
Child.prototype.constructor = Child
const parent = new Parent()
const child1 = new Child()
// const child2 = new Child()
// child1.name[0] = '彭于晏的胸大肌'
console.log(child1.getName()); //熊大
// console.log(child2.name);
console.log(parent.getName()); //undefined,验证浅拷贝的成功与否