반응형
위임형 상속(Delegation inheritance)
프로토타입 객체는 다른 객체의 기반이되며,
위임 프로토타입을 상속받을 경우 새 객체는 해당 프로토타입에 대한 참조를 가짐
function Person(name){
this.name = name;
}
Person.prototype.setName = function(name){
this.name = name;
}
Person.prototype.getName = function(){
return this.name;
}
Person이라는 함수를 만들고 Person.prototype으로 객체의 공용 메서드를 작성
function Student(name, major){
this.major = major;
}
Person(부모)을 상속받을 Student를 major 멤버변수를 추가해 생성
const me = new Person("jane");
Student.prototype = me;
Student.prototype에 Person 객체를 상속
Student.prototype.setMajor = function(major){
this.major = major;
}
Student.prototype.getMajor = function(){
return this.major;
}
Student에서 추가한 멤버변수의 getter 와 setter 작성
→ 기존 부모 객체에서 멤버변수를 추가하려면 상속을 받고 이후 멤버변수에 대한 getter와 setter 를 작성
const man = new Student("tom", "computer engineering");
console.log(man);
man.setName("tommy");
man.setMajor("EECS");
console.log(man);
활용
구조
man.getName();
man이라는 새 객체의 getName 속성에 접근 시, 해당 객체가 직접적으로 속성을 소유하고 있는지 체크하고
직접적으로 가진 속성이 아니라고 판단하면 prototype을 확인
'JavaScript' 카테고리의 다른 글
[JavaScript] click event 로 글자 색을 번갈아가며 변경하는 3가지 방법 (0) | 2021.09.13 |
---|---|
[Spring] Eclipse Spring Legacy Project 세팅 (0) | 2021.09.06 |
[JavaScript] 프로토타입 기반의 자바스크립트와 상속 (0) | 2021.09.05 |
[JavaScript] Document Object (0) | 2021.09.04 |
[JavaScript] 스코프(Scope)와 변수 var, let, const (0) | 2021.09.03 |