본문 바로가기
JavaScript

[JavaScript] 프로토타입 기반의 자바스크립트와 상속

by jane.dev 2021. 9. 5.
반응형
프로토타입 기반 프로그래밍
객체 지향 프로그래밍과 달리 어떠한 객체를 생성할 때, 
처음 그 객체의 클래스를 정의하지 않는 것을 허용

 

→ 클래스 기반 언어에서 상속을 사용하는 것과 다르게 객체를 원형(프로토타입)으로 하여 복제의 과정을 통해 객체의 동작 방식을 다시 사용

 

function Person(name){
    this.name = name;
    
    this.getName = function(){
        return this.name;
    }

    this.setName = function(name){
        this.name = name;
    }
}

Person이라는 함수를 만들어, 함수 내부에 this 키워드를 이용해 변수를 만들고 함수를 대입하면 클래스처럼 사용가능

 

const me = new Person("jaein");
me.setName("jane");
console.log(me.getName());

const man = new Person("tom");
man.setName("tommy");
console.log(man.getName());

const woman = new Person("sammy");
woman.setName("sammmmmy");
console.log(woman.getName());

new 키워드로 객체를 생성해서 호출시마다 함수를 생성하게되는 문제점이 나타나며, 서로 다른 주소에 데이터를 저장하여 메모리 누수 발생

 

pythontutor.com

 

JavaScript는 객체가 공용으로 사용해야하는 메서드에 대해서 프로토타입을 제공함

function Person(name){
    this.name = name;
}

객체가 개별적으로 가져야하는 멤버변수만 선언하고 클래스 정의

 

Person.prototype.getName = function(){
    return this.name;
};

Person.prototype.setName = function(name){
    this.name = name;
};

'클래스명.prototype' 은 모든 객체의 공용공간으로 사용하여 메서드를 직접 저장

 

const me = new Person("jaein");
me.setName("jane");
console.log(me.getName());

const man = new Person("tom");
man.setName("tommy");
console.log(man.getName());

const woman = new Person("sammy");
woman.setName("sammmmmy");
console.log(woman.getName());

Person 함수로 생성된 객체 me, man, woman

 

pythontutor.com

 

Person.prototype 이라는 object를 만들어 getName, setName 을 me, man, woman이 공유해서 사용 가능