<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>js所有的继承方法优缺点</h1>
<script>
//定义构造函数
/*
一、原型链继承:优缺点
优点:父类方法可以复用
缺点:1.父类所有的引用类型(对象/数组)数据会被所有子类共享,更改一个子类的数据,其他数据也会跟着受到影响,一起变化
2.子类实例不能给父类传参
二、构造函数继承
优点:子类的引用类型数据不会被子类共享 每new 一个就是一个新的父类参数的值
缺点:子类不能访问父类原型上的方法和参数
三、组合继承
优点:继承了原型链继承和组合继承的优点 父类可以复用,并且父类构造函数中的引用属性数据不会被共享
缺点:他会调用两次父类的构造函数,浪费性能 会有两份一样的属性和方法
四、寄生组合继承
优点:完美继承
缺点:代码多
*/
function Person(){
this.name = '小明'
this.a = ['苹果']
//在这个地方如果使用箭头函数的话 this指向会改变为未修改后的
this.getName = function() {
console.log(this.name);
}
}
Person.prototype.get = () => {
console.log('Person.prototype 上的方法');
}
function Student(){
//构造函数继承
Person.call(this);
}
//原型链继承 就是直接子类的prototype = 父类的prototype
//构造函数继承则是,在子类的构造函数中调用父类的构造函数更改this指向 但是构造函数
//两个都放开的话就是组合继承
//寄生组合继承就是他们的结合体 实现的话就是需要把父类的proptotype赋值给一个空的prototype就可以了
function fn(){}
fn.prototype = Person.prototype
Student.prototype = new fn()
const stu1 = new Student()
stu1.name = '小花'
stu1.a.push('香蕉')
console.log(stu1.name);
console.log(stu1.a);
stu1.getName()
stu1.get()
console.log('-----------------------------');
const stu2 = new Student()
console.log(stu2.name);
console.log(stu2.a);
stu2.getName()
console.log(new Student());
</script>
</body>
</html>