본문 바로가기
JavaScript

[JavaScript] 프로토타입을 활용한 상속

by jane.dev 2021. 9. 5.
반응형
위임형 상속(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);

활용

 

pythontutor.com

 

구조

 

man.getName();

man이라는 새 객체의 getName 속성에 접근 시, 해당 객체가 직접적으로 속성을 소유하고 있는지 체크하고

직접적으로 가진 속성이 아니라고 판단하면 prototype을 확인