반응형
자바스크립트의 프로토 타입, 클래스에 대해 알아보는 시간을 가진다.
1. 프로토타입 (prototype)
- 프로토 타입은 JS에 클래스가 생기기전 객체를 다를 객체로 상속하기 위해 사용하는 개념이다 (ES6의 클래스는 타 언어의 클래스와 거의 흡사하고, 내부적으로는 prototype을 따른다고 함)
- 앞서 JS에서 객체 생성자란 무엇인지, 상속은 어떤방식으로 하는지 간단하게 확인해보자.
function People(name, age) {
this.name = name;
this.age = age;
this.info = function() {
console.log('이름: ' + name);
console.log('나이: ' + age);
}
}
const test = new People('A', '30');
const test2 = new People('B', '20');
test.info();
test.info();
- 결과는 예상한대로 이름 : A, 나이 :30 이름: B, 나이: 20이 나온다.
여기서 프로토타입을 사용하면 다음과 같이 바뀐다.
function People(name, age) {
this.name = name;
this.age = age;
}
People.prototype.info = function() {
console.log('이름: ' + this.name);
console.log('나이: ' + this.age);
}
const test = new People('A', '30');
const test2 = new People('B', '20');
test.info();
test.info();
그렇다면 프로토타입을 사용했을때 무엇이 달라질까?
- 프로토 타입을 사용하지 않은경우 객체하나를 생성할때마다 info라는 메소드가 할당된다. 즉 2개의 객체를 생성하면 2개의 info가 할당되는 셈이다
- 반면 프로토타입을 사용한경우 People객체는 하나의 info메소드를 생성하고 객체에서 참조하여 사용하게 된다.
즉 2개의 객체를 생성했지만 info 메소드는 1개만 생성되는 차이가 있다.
- 이로서 프로토 타입은 불필요한 메모리 낭비를 막을 수 있는 중요한 개념이다.
프로토타입을 이용한 상속은 다음과 같다.
function People(name, age) {
this.name = name;
this.age = age;
}
People.prototype.info = function() {
console.log('이름: ' + this.name);
console.log('나이: ' + this.age);
}
function Child (name, age) {
People.call(this, name, age);
}
Child.prototype = People.prototype;
const child = new Child('test', '30');
child.info();
2. 클래스
- 타언어의 클래스와 매우 유사하다 (JAVA, C...등)
ES6에서 새로 생긴 문법으로 기존 prototype을 활용한 객체 생성자를 클래스로 더 쉽게 표현할 수 있다.
class People {
constructor(name, age) {
this.name = name;
this.age = age;
this.info = function() {
console.log('이름 :' + this.name);
console.log('나이 :' + this.age);
}
}
}
const people = new People('A', '10');
people.info();
- 클래스 상속은 다음과 같다.
class People {
constructor(name, age) {
this.name = name;
this.age = age;
this.info = function() {
console.log('이름 :' + this.name);
console.log('나이 :' + this.age);
}
}
}
class Child extends People {
constructor(name, age) {
super(name, age);
}
}
const child = new Child('A', '10');
child.info();
반응형
'프로그래밍 > Javascript' 카테고리의 다른 글
[JS] 호이스팅, Hoisting 이란? (0) | 2022.06.01 |
---|---|
[Javascript] 자바스크립트 실행컨텍스트란? (0) | 2021.12.27 |