Inspired World

JavaScript 에서 객체지향 프로그래밍(OOP) 하기 본문

JavaScript

JavaScript 에서 객체지향 프로그래밍(OOP) 하기

InspiredJW 2012. 3. 9. 10:40
JavaScript에서

procedural programmingobject oriented programing을 모두 할 수 있습니다.

의외로 Object Oriented Programming ( 객체지향 프로그래밍 ), OOP 이 가능한지 모르시는 분들이 있어

이번 포스팅에서 소개하기로 했습니다.



먼저 객체 생성자 (Constructor)를 만들어볼까요?

* 소멸자 (Destructor)는 따로 정의 안해도 됩니다. 기본적으로 JavaScript는 Garbage Collection을 하니까요.

 

var Person = function ( info ) {
    this.height = info.height || '178cm';
    this.weight = info.weight || '72kg';
    this.name = info.name || 'InspiredJW';
};

이렇게 하면 Person 이라는 객체의 기본 Property를 정의하게 됩니다. 또 Constructor에서 호출할 함수가 있으면

여기서 호출하면 됩니다.


여기서는 info라는 JSON에서 height, weight, name 이 정의가 되어 있으면 그 값을 객체의 height, weight, name

Property에 할당하고 아니면 기본값을 할당하게 됩니다.

 
Person.prototype.whoAreYou = function () {
     alert( 'My Name Is ' + this.name );
};

이렇게 method도 정의할 수 있는데요.

예를 들어

 
var Tom = new Person( { name:"Tom", height:"183cm", weight:"77kg" } );

Tom.whoAreYou();

이렇게 하면 첫번째 줄에서 

이름이 Tom 이고 키가 183cm 이며 몸무게가 77kg 인 사람 객체를 생성하게 되고

두번째 줄에서는 Tom 이라는 객체의 함수인 whoAreYou() 를 호출하게 되어

자신의 이름을 alert 창을 통해 말하게 됩니다.

"My Name Is Tom"


상속(Inheritance)나 다형성(Polymorphism) 또한 JavaScript에서 가능합니다.


var Student = function () {  
    // Call the parent constructor  
    Person.call(this);  
}  
  
// Person 객체 상속
Student.prototype = new Person();  
  
// 생성자(constructor)의 포인터가 Person으로 된것을 Student 로 수정
Student.prototype.constructor = Student;  
   
// Override whoAreYou method
Student.prototype.whoAreYou = function () {  
  alert( 'Student ' + this.name );  
}  

이렇게 하면 Student는 Person 객체의 모든 property와 method를 상속받게 되고

위의 경우 whoAreYou method를 override하여 method를 재정의하게 됩니다. 
Comments