본문 바로가기
JavaScript

[JavaScript]객체 지향 프로그래밍

by eddypark 2023. 10. 18.

(1) 프로토타입 기반 언어

- JavaScript는 프로토타입 기반 객체 지향 언어이다.

- 상속, 캡슐화 개념은 체인과 클로저등으로 구현 가능하다.

- 생성자 함수와 new연산자를 통해 객체 생성할 수 있다.

- 프로토타입 방법을 쓰면 상속이 가능하기 때문에 메모리의 양을 줄일 수 있다.

///생성자 함수///
function Point(x,y){
	this.x = x; 
	this.y = y;
	this.sum = function(){
		return this.x + this.y;
	}
}
point1 = new Point(5,5); 
point2 = new Point(8,8); 

console.log(point1);       // Point { x: 5, y: 5, add: [Function] }
console.log(point1.sum()); // 10
console.log(point2);       // Point { x: 8, y: 8, add: [Function] }
console.log(point2.sum()); // 16

///프로토 타입 방법///

function Point(x,y){ 
	this.x = x; 
	this.y = y; 
}

Point.prototype.add = function(){ 
	return this.x + this.y; 
} 

point1 = new Point(5,5); 
point2 = new Point(8,8); 

console.log(point1.add()); // 10 
console.log(point2.add()); // 16

(2) 상속

- JavaScript는 기본적으로 프로토 타입을 통해 상속한다.

- 객체가 또 다른 객체로 직접 상속된다는 의미다.

- 코드 재사용을 하여 개발 비용이 현저히 줄어든다.

- 의사 클래스 패턱 상속 : 부모와 자식 모두 생성자 함수를 정의해야 하며, 자식 생성자 함수의 prototype 프로퍼티를 부모 생성자 함수의 인스턴트로 교체하여 상속하는 방법이다.

var Parent = function () {                        // 부모 생성자 함수
  function Parent(name) {                         // 생성자
    this.name = name;
  }

  Parent.prototype.sayHi = function () {          // method
    console.log('Hi! ' + this.name);
  };

  return Parent;                                  // return constructor
}();


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

	Child.prototype = new Parent();               // 자식 생성자 함수의 프로토타입 객체를 부모 생성자 함수의 인스턴스로 교체


	Child.prototype.sayHi = function () {
    	console.log('안녕하세요! ' + this.name);  // 메소드 오버라이드
  	};

	Child.prototype.sayBye = function () {        // sayBye 메소드는 Parent 생성자함수의 인스턴스에 위치된다
    	console.log('안녕히가세요! ' + this.name);  
  	};

	return Child;                                 // return constructor
}();

var child = new Child('child');
console.log(child);                               // Parent { name: 'child' }

console.log(Child.prototype);                     // Parent { name: undefined, sayHi: [Function], sayBye: [Function] }

child.sayHi();                                    // 안녕하세요! child
child.sayBye();                                   // 안녕히가세요! child

console.log(child instanceof Parent);             // true
console.log(child instanceof Child);              // true

- 프로토타입 패턴 상속 : 프로토타입으로 상속을 구현. 의사 클래스 패턴 상속보다 간단하다. 또한 new연산자가 필요 없다.

var Parent = function () {
  function Parent(name) {                    // 생성자
    this.name = name;
  }

  Parent.prototype.sayHi = function () {
    console.log('Hi! ' + this.name);
  };

  return Parent;
}();

var child = Object.create(Parent.prototype);  // create 함수의 인수는 프로토타입이다.
child.name = 'child';

child.sayHi();                                // Hi! child

console.log(child instanceof Parent);         // true

'JavaScript' 카테고리의 다른 글

[JavaScript]Global Object  (1) 2023.10.19
[JavaScript]Built-in Object  (0) 2023.10.19
[JavaScript]클로저(closure)  (0) 2023.10.18
[JavaScript] 실행 컨텍스트(Execute Context)  (0) 2023.10.17
[JavaScript] this  (1) 2023.10.17