Chapter 06 - norux/javascript_study GitHub Wiki

6. 객체지향 프로그래밍

자바스크립트 역시 다음 특성을 가지는 객체지향 프로그래밍이 가능하다.

객체지향 언어의 특성

  • 클래스, 생성자, 메서드
  • 상속
  • 캡슐화

클래스기반의 언어와 프로토기반 언어

  • java, c++과 같은 언어가 클래스 기반의 언어이다.
  • javascript는 프로토타입 기반의 언어이다.

6.1 클래스, 생성자, 메서드

  • java, c++에서는 class라는 키워드를 통해 클래스를 만들어 낸다.
  • 자바스크립트는 함수 객체를 이용하여, 클래스, 생성자, 메서드를 구현한다.

예제코드

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

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

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

var me = new Person( "heebum" );
console.log( me.getName() );  // heebum

me.setName( "noru" );
console.log( me.getName() ); // noru


//이 코드의 문제점
var me = new Person( "me" );
var you = new Person( "you" );
var him = new Person( "him" );

  • 모든 중복되는 함수들을 메모리에 올려놓고 사용하게 된다.
  • 이를 해결하는 코드는 다음과 같다.
function Person( arg ) {
  this.name = arg;
}

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

var me = new Person( "me" );
var you = new Person( "you" );