常用的继承方法:
1.原生继承
/ 抽取共同点
/* 人类 */
function People(name, age, sex) {
this.name = name;
this.age = age;
this.sex = sex;
}
People.prototype.say = function() {
console.log("hahahahha");
}
People.prototype.breath = function() {
console.log("hu~~~~~xi~~~~~");
}
/* 学生类 */
function Student (name, age, sex, studentNO) {
// this 是Student的实例
// 构造函数式继承 也叫做类式继承
People.call(this, name, age, sex); // People被执行 并 this改为Student的实例 等价于以下三条 之所以这么写是为了复用代码
// this.name = name;
// this.age = age;
// this.sex = sex;
this.studentNO = studentNO;
}
// Student既然继承了People除了要有People的属性之外 还要有People的方法
// 将Student的原型指向People的实例 叫做原型式继承
Student.prototype = new People();
// 因为丢了原来的原型 所以constructor属性也就丢失了需要补回
// 补回操作与增加新方法的操作 一定要在继承完毕之后再执行
Student.prototype.constructor = Student;
Student.prototype.study = function() {
console.log("学习");
}
/* 老师类 */
function Teacher(name, age, sex, jiaobian) {
People.call(this, name, age, sex);
this.jiaobian = jiaobian;
}
Teacher.prototype = new People();
// delete Teacher.prototype.name;
// delete Teacher.prototype.age;
// delete Teacher.prototype.sex;
Teacher.prototype.constructor = Teacher;
Teacher.prototype.teach = function() {
console.log("教书");
}
2.寄生式
// 想要让学生类的实例拥有People类的方法
// var F = function() {
// }
// F.prototype = People.prototype;
// var f = new F();
3.构造式:构造函数式继承 它是专门用于继承属性的
People.call(this, name, age, sex);
4.Es6中的继承
<script>
// ES6中的定义类
class People {
// 类中的构造函数
constructor(name, age, sex) {
// 属性定义在这里
this.name = name;
this.age = age;
this.sex = sex;
}
// 方法定义在这里
breath() {
console.log("呼~~~~吸~~~~");
}
}
// ES6中的继承
class Student extends People {
constructor(name, age, sex, studentNO) {
// 必须调用super
super(name, age, sex);
this.studentNO = studentNO;
console.log("hahahaha")
}
}
// 初始化实例
var s = new Student("小白", 15, "男", 123);
</script>