<script>
// 原型链继承
// 父类
function Parent(name) {
this.name = name
}
// 父类的原型方法
Parent.prototype.getName = function() {
return this.name
}
const parent = new Parent("张三")
console.log(parent.name)
// 子类
function Children(){
}
Children.prototype = new Parent("李四")
Children.prototype.constructor = Children
const child = new Children()
console.log(child.name)
// 原型链继承缺点 由于都是通过父类的实例实现继承,因为浅拷贝的存在会导致一个实例的改变导致其他的也跟着变化
// 构造函数继承
function Son(){
Parent.call(this,"王二麻子")
}
const son = new Son()
console.log(son.name)
// console.log(son.getName())
// 构造函数继承缺点 不能具有父类原型上的方法和属性
// 组合继承
function Daugther(){
Parent.call(this,"小石")
}
Daugther.prototype = new Parent()
Daugther.prototype.constructor = Daugther
const dau = new Daugther()
console.log(dau.name)
console.log(dau.getName())
// 组合继承缺点 执行了两次构造函数,分别是new Parent()和Parent.call()
// 寄生组合继承
function Ji(){
Parent.call(this,"寄生")
}
Ji.prototype = Object.create(Parent.prototype) // 深拷贝
Ji.prototype.constructor = Ji
</script>
Not Comment Found