6. 자바스크립트 객체지향 프로그래밍 #1 클래스, 생성자, 메서드

2021. 11. 11. 13:43JavaScript/basic

이전글

https://yonghwankim-dev.tistory.com/164

 

5. 실행 컨텍스트와 클로저 #4 클로저(Closure)

이전글 https://yonghwankim-dev.tistory.com/163 5. 실행 컨텍스트와 클로저 #3 스코프 체인 이전글 https://yonghwankim-dev.tistory.com/162 5. 실행 컨텍스트와 클로저 #2 실행 컨텍스트 생성 과정 이전글 htt..

yonghwankim-dev.tistory.com

 

본 글은 INSIDE JAVASCRIPT 도서의 내용을 복습하기 위해 작성된 글입니다.

 

6장 목차

1. 클래스, 생성자, 메서드

2. 상속

3. 캡슐화

4. 객체지향 프로그래밍 응용 예제

 

1. 자바스크립트의 프로토타입과 new 연산자를 활용한 클래스, 생성자 정의 및 객체 생성

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

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

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

var kim = new Person("kim");
console.log(kim.getName()); // Expected Output : kim

kim.setName("lee");
console.log(kim.getName()); // Expected Output : lee

위 예제를 통하여 함수 Person이 클래스이자 생성자의 역할을 수행합니다. 그리고 new 키워드를 사용하여 객체를 생성할 수 있습니다. 하지만 위 예제는 문제점이 존재합니다. 그것은 객체를 생성 할 때마다 각각의 객체가 getName(), setName() 함수를 가지고 있어서 메모리 공간을 차지하는 문제점이 있습니다. 예를 들어 아래의 코드를 통하여 객체를 생성하였다고 가정합니다.

var kim = new Person("kim");
var lee = new Person("lee");
var park = new Person("park");

위의 객체 생성으로 인하여 메모리 상황은 아래 그림과 같을 것입니다.

이 문제를 해결하기 위해서 Person 함수 객체의 프로토타입 객체에 함수를 정의하면 해결할 수 있을 것입니다.

 

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

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

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

const kim = new Person("kim");
const lee = new Person("lee");

console.log(kim.getName());     // Expected Output : kim
console.log(lee.getName());     // Expected Output : lee

위와 같이 Person.prototype 프로토타입 객체에 getName(), setName() 함수를 정의하여 Person 객체가 한 공간의 함수만을 참조하도록 하였습니다. 위 관계를 그림으로 표현하면 아래와 같습니다.

 

2. 메서드 정의

더글라스 크락포드는 다음과 같은 함수를 제시하면서 메서드를 정의하는 방법을 소개합니다.

Function.prototype.method = function(name, func){
    if(!this.prototype[name]){
    	this.prototype[name] = func;
    }
}

위 코드의 method 함수의 내용은 특정한 함수 객체의 프로토타입 객체에 name에 따른 함수가 존재하지 않으면 그 name에 따른 함수를 func 함수 내용으로 추가하는 내용입니다.

 

위 함수를 이용한다면 아래와 같은 형태가 됩니다.

Function.prototype.method = function(name, func){
    this.prototype[name] = func;    // this->Person
}

// 생성자 함수
function Person(name){
    this.name = name;
}

// 메서드 정의
Person.method("getName",function(){
    return this.name;
});

Person.method("setName",function(name){
    this.name = name;
});

const kim = new Person("kim");
const lee = new Person("lee");

console.log(kim.getName());     // Expected Output : kim
console.log(lee.getName());     // Expected Output : lee

// Person.method("getName",function(){return this.name;});
// => Person.prototype["getName"] = function(){ return this.name; }

 

 

References

source code : https://github.com/yonghwankim-dev/javascript_study
송형주, 고현준 저, 『인사이드 자바스크립트』, 한빛미디어(2014)