javascript 계승 방안 - 원형 계승
주: 원형 계승 을 깊이 이해 하려 면 먼저 자바 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 가 모두 변 했 습 니 다.
이 내용에 흥미가 있습니까?
현재 기사가 여러분의 문제를 해결하지 못하는 경우 AI 엔진은 머신러닝 분석(스마트 모델이 방금 만들어져 부정확한 경우가 있을 수 있음)을 통해 가장 유사한 기사를 추천합니다:
다양한 언어의 JSONJSON은 Javascript 표기법을 사용하여 데이터 구조를 레이아웃하는 데이터 형식입니다. 그러나 Javascript가 코드에서 이러한 구조를 나타낼 수 있는 유일한 언어는 아닙니다. 저는 일반적으로 '객체'{}...
텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
CC BY-SA 2.5, CC BY-SA 3.0 및 CC BY-SA 4.0에 따라 라이센스가 부여됩니다.