javascript继承方案 -- 构造函数继承

构造函数继承

注:要了解构造函数继承请先了解 call apply 的用法

/**
 * 构造函数继承
 * 实现方法: 在子类构造函数中通过call, apply调用父类构造函数
 * 优点:可以通过此继承实现继承父类实例的属性和方法
 * 缺点:无法继承父类prototype上的方法,每个子类都有父类实例函数的副本,影响性能
 */

function Person (job) {
  this.job = job;
  this.habit = ["eat", "drink", "sleep"];
}

Person.prototype.printHabit = function () {
  console.log(this.habit);
};

Person.prototype.printJob = function () {
  console.log(this.job);
};

function Student(name, job) {
  this.name = name;
  Person.call(this, job);
}

Student.prototype.printName = function () {
  console.log(this.name)
};

function Teacher(name) {
  this.name = name;
  Person.call(this);
}

const person = new Person("people");

const student = new Student("leo", "student");
student.habit.push("read");

const teacher = new Teacher("MrLiu");
teacher.habit.push("teach");

person.printHabit(); // ["eat", "drink", "sleep"]
person.printJob(); // people
console.log(person.printName); // undefined

console.log("------------------------------");

console.log(student.name); // leo
console.log(student.job); // student
console.log(student.habit); // ["eat", "drink", "sleep", "read"]

console.log(student.printHabit); // undefined
console.log(student.printJob);// undefined
student.printName(); // leo

console.log("------------------------------");

console.log(teacher.name); // MrLiu
console.log(teacher.job); // undefined
console.log(teacher.habit); // ["eat", "drink", "sleep", "teach"]

console.log(teacher.printHabit); // undefined
console.log(teacher.printJob); // undefined
console.log(teacher.printName); // undefined

你可能感兴趣的:(javascript继承方案 -- 构造函数继承)