#13. 객체 지향 프로그래밍(2)

2langk·2021년 3월 22일
0

[오분자스 - 개념편]

목록 보기
13/24
post-thumbnail

Object Oriented Programming(2)

앞 포스트에서 객체와 생성자 함수가 무엇인지 알아보았다. 이번에는 prototype이 어떻게 활용되는지 알아보도록 하자.

1. prototype
지난 시간의 예제이다.

예시1)

const Student = function(name, age) {
  this.name = name;
  this.age = age;
  this.sayHello = function() {
    return 'Hello!'
  }
}


const student1 = new Student('lee', 20);
const student2 = new Student('kim', 21);
	...
const student30 = new Student('park', 22);

이렇게 객체를 생성했을때 발생하는 에러는 없지만,
생성된 모든 객체가 sayHello라는 동일한 메소드를 가지고 있다는 점이 메모리 측면에서 비효율적이다.

이 문제를 해결할 수 있는게 바로 prototype이다

prototype을 이용해서 객체가 직접 메소드를 갖는것이 아니라 메소드를 공유하게 할 수 있다.
어떻게 하는지 아래 코드로 보자.

예시2)

const Student = function(name, age) {
  this.name = name;
  this.age = age;
}

Student.prototype.sayHello = function() {
  return 'Hello!'
}

const student1 = new Student('lee', 20);
const student2 = new Student('kim', 21);
	...
const student30 = new Student('park', 22);

메소드를 생성자 함수에 포함시키는게 아닌 프로토타입으로 분리했다.

지금 예시1과 예시2가 어떻게 다른지 이해하려면 앞에서 설명한 proto와 prototype 관계를 기억하고 있어야 한다.


우리는 생성자 함수 Student로 객체 student1~30을 생성했다.

student1.__proto__ === Student.prototype // true

student2.__proto__ === Student.prototype // true

student30.__proto__ === Student.prototype // true

따라서 위의 관계가 성립되며, student 객체들은 Student의 prototype를 사용할 수 있다.

student1.sayHello() // Hello!
student2.sayHello() // Hello!
	... 

정리하면, 예시1)에서는 객체가 n개 생성되면 sayHello 메소드도 n개가 필요했지만,
예시2)에서는 객체가 몇 개가 생성되든 sayHello 메소드는 딱 1개만 필요하게 되었다.

이번 시간은 여기서 마무리하고,
다음 시간에는 prototype에 메소드를 정의할 때 주의할 점에 대해 써보도록 하겠다.

0개의 댓글