原型继承
// 原型继承
function Person(name, age) {
this.name = name;
this.age = age;
this.eat = function () {
console.log("吃货");
}
}
// 通过原型继承实现了方法的继承
Student.prototype = new Person();
Student.prototype.constructor = Student;
function Student(name, age) {
this.name = name;
this.age = age;
}
var s1 = new Student("张三", 22, "男");
s1.eat(); // eat方法继承
属性继承
// 属性继承
// 通过call或apply来改变this指向,实现属性的继承
function Person(name, age, sex, height, weight, faceValue) {
this.name = name;
this.age = age;
this.sex = sex;
this.height = height;
this.weight = weight;
this.faceValue = faceValue;
}
function Student(name, age, sex, height, weight, faceValue, grade) {
// this.name = name;
// this.age = age;
// this.sex = sex;
// this.height = height;
// this.weight = weight;
// this.faceValue = faceValue;
Person.call(this, name, age, sex, height, weight, faceValue);
this.grade = grade;
}
var s1 = new Student("张三", 18, "男", 175, 140, 50, 3);
console.log(s1);
组合继承
// 既想属性继承,又想方法继承 -> 组合继承
function Person(name, age, sex, height, weight, faceValue) {
this.name = name;
this.age = age;
this.sex = sex;
this.height = height;
this.weight = weight;
this.faceValue = faceValue;
}
Person.prototype.eat = function () {
console.log("吃货");
}
Student.prototype = new Person();
Student.prototype.constructor = Student;
function Student(name, age, sex, height, weight, faceValue, grade) {
Person.call(this, name, age, sex, height, weight, faceValue);
this.grade = grade;
}
var s1 = new Student("张三", 18, "男", 175, 140, 50, 3);
console.log(s1);
s1.eat();
方法重写与方法重载(多态的表现形式)
// 方法重写和方法重载(多态的表现形式)
// 方法重写 -> 覆盖之前的方法
Person.prototype.eat = function (type) {
// 方法重载 -> 不同的功能,可以根据参数来判断
if (type == "学生") {
console.log("吃的很多");
} else if (type == "人") {
console.log("吃的很少");
}
}
s1.eat("学生");
new Person().eat("人");