클래스란?
- Class의 경우 프로토타입 기반으로 동작을 함,
class
키워드를 사용하고 생성자에 대해선 constructor
메소드를 통해서 할 수 있음
- 함수 표현식 & 선언 모두 클래스에서 사용할 수 있음
- Class를 사용해도 결국 내부적으로는 프로토타입 기반으로 사용되서 활용되는 것임
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
}
인스턴스란?
- 클래스, 생성자 함수로 인스턴스를 아래와 같이 만들 수 있음
- 인스턴스는 실제 메모리에 올라가고 고유한 값이지만, 이를 생성자 함수와 클래스로 만들어도 큰 차이가 없음(싱글 리터럴도 하나의 객체, 인스턴스로 볼 수 있음)
function Func() {}
const newInstance = new Func();
class Classes {}
const newInstance2 = new Classes();
클래스와 인스턴스
- 아래의 2개의 예시로 클래스를 사용하지 않고 했던 기존의 방식에서 클래스를 사용한 방식으로 동일하게 동작하되, 클래스를 쓴 방식에 대해 이해할 수 있음
function Person(name, age, location) {
this.name = name;
this.age = age;
this.location = location;
}
Person.prototype.getName = function () {
return this.name + '입니다';
};
const me = new Person('kevin', 10, 'Korea');
const you = new Person('hart', 20, 'China');
me.getName();
you.getName();
class Person {
constructor(name, age, location) {
this.name = name;
this.age = age;
this.location = location;
}
getName() {
return this.name + '입니다';
};
}
const me = new Person('kevin', 10, 'Korea');
const you = new Person('hart', 20, 'China');
me.getName();
you.getName();
- 사용새도, 쓰임새도 동일하고 템플릿도 쉬움 getter, setter도 동일하게 Class에서 쓸 수 있음
클래스 확장
- 아래와 같이 앞서 프로토타입과 생성자 함수 쓴 것을 Class 형태로 변환해서 확장도 마찬가지로 처리할 수 있음
- 그리고 명시적인 바인딩의 경우도
extends
로 만으로 확장을 쉽게함, 그리고 부모의 대한 확장을 call 메소드가 아닌 super
키워드를 통해서 부모를 확장함
class Animal {
constructor(name, sound) {
this.name = name;
this.sound = sound;
}
getInfo() {
return (
this.name +
'가(이)' +
this.sound +
' 소리를 낸다.'
);
}
}
class Friends extends Animal {
constructor(name, sound) {
super(name, sound);
}
}
const dog = new Friends('개', '멍멍');
const cat = new Friends('고양이', '냐옹');
dog.getInfo();
cat.getInfo();
dog.constructor.name
cat.constructor.name
dog instanceof Friends;
dog instanceof Animal;
- 생성자 함수 사용 없이, 클래스만으로 쉽게 확장을 하고 내부 동작을 코드로 구현하지 않고 쉽게 처리함