객체의 프로퍼티에 접근하려고 할 때 해당 객체에 접근하려는 프로퍼티가 없다면 자신의 부모 역할을 하는 프로토타입의 프로퍼티를 순차적으로 검색하는것
객체 지향 프로그래밍의 특성 중 상속을 JavaScript에서 구현할 때에는 프로토타입 체인을 사용합니다.
function Human(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
this.eat = function() {};
this.sleep = function() {};
}
let kimcoding = new Human('김코딩', 16, '남');
// 속성
kimcoding.name;
kimcoding.age;
kimcoding.gender;
// 메서드
kimcoding.eat();
kimcoding.sleep();
위를 보면 사람은 기본적으로 age(나이)와 gender(성별)을 가지고있고 먹기(eat), sleep(자기)라는 행동을 한다.
하지만 학생이라고 나이와 성별을 가지지 않는것은 아니다
학생은 기본적으로 grade(학년)라는 속성과 learn(배움)이라는 메서드가 있다.
function Student (grade) {
this.grade = grade;
this.learn = function() {};
}
// __proto__를 사용하여 human의 속성을 상속받음
let parkhacker = new Student(6);
parkhacker.__proto__ = kimcoding;
// 속성
parkhacker.grade;
// 메서드
parkhacker.learn();
Object를 사용하여 상속도 가능하다
function Human(name, age, gender) {
this.name = name;
this.age = age;
this.gender = gender;
this.eat = function() {};
this.sleep = function() {};
}
// Human을 상속받았다
let kimcoding = new Human('김코딩', 16, '남');
kimcoding.learn = function() {}
let student = Object.create(kimcoding);