javascript 계승 방안 - 원형 계승

2141 단어
원형 계승
주: 원형 계승 을 깊이 이해 하려 면 먼저 자바 script 원형 체인 을 알 아야 합 니 다. 그렇지 않 으 면 아래 에 보 이 는 얼굴 이 어 리 석 습 니 다.
/**
 *      
 *     :   prototype           
 *   :                
 *   :       prototype            ,     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);
};

//        
const person = new Person("people");

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

//   Student prototype    Person   (    )
Student.prototype = person;

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

//   Student     
const student = new Student("leo", "student");

//   Student           (  habit  )
student.habit.push("read");

//   Teacher    
function Teacher(name) {
  this.name = name;
}

//   Teacher prototype    Person   (    )
Teacher.prototype = person;

//   Teacher     
const teacher = new Teacher("MrLiu");

//   Teacher           (  habit  )
teacher.habit.push("teach");


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

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

student.printHabit(); // ["eat", "drink", "sleep", "read", "teach"]
student.printJob(); // student
student.printName(); //leo

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

teacher.printHabit(); // ["eat", "drink", "sleep", "read", "teach"]
teacher.printJob(); // people
teacher.printName(); // MrLiu

인쇄 결 과 를 보면 하위 클래스 가 부모 클래스 를 계승 하 는 방법 을 알 수 있 습 니 다. 하위 클래스 Student 가 prototype 에 printName 방법 을 추 가 했 기 때문에 person student teacher 는 모두 printName 방법 을 가지 게 되 었 습 니 다. 또한 그들 이 공유 하 는 속성 habit 는 인용 형식 이기 때문에 세 개의 habit 가 모두 변 했 습 니 다.

좋은 웹페이지 즐겨찾기