JavaScript
[JS] Class vs Object 객체지향 언어 클래스 정리
Leo(상원)
2022. 10. 10. 17:42
반응형
1. Class 의 개념과 선언방법
class Person {
// constructor 생성자
constructor(name, age) {
//fields
this.name = name
this.age = age
}
// Methods
speak() {
console.log(`${this.name}: hello!`)
}
}
// 객체 생성
// 객체를 생성할 때에는 클래스앞에 new라는 키워드를 사용한다.
const leo = new Person("leo", 26)
console.log(leo.name)
leo.speak()
Class
- 자바스크립트 클래스는 ES6에서 새로 나온 문법이다.
- 클래스는 템플릿에 속하고 데이터가 들어있지 않고 템플릿만 정의합니다.
- 클래스는 한번만 선언합니다.
- 클래스는 최신문법이여서 나오기 이전에는 객체를 함수형식의 템플릿으로 만들어 사용하였습니다.
- 기존에 존재하던 프로토 타입을 베이스를 기반하여 문법만 클래스로 추가한 것이다. (syntactical sugar)
Object
- instance of a class 클래스의 인스턴스 입니다.
- 1개의 클래스로 여러 객체를 만들수 있습니다.
- 객체 안에는 데이터가 있습니다.
2. Getter and Setters
Getter 는 객체의 특정 프로퍼티 값을 가져오는 메소드입니다.
Setter 는 객체의 특정 프로퍼티 값을 수정하는 메소드입니다.
class User {
constructor(age) {
this.age = age
}
get age() { // 인자를 받지 않습니다.
return this._age
}
set age(value) { // 인자를 받아 할당합니다.
this._age = value < 0 ? 0 : value
}
}
// -1이 나이가 되면 안되기에 setter에서 수정해줍니다.
const user1 = new User(-1)
- getter 와 setter 안에서 사용되는 프로퍼티는 이름앞에 관습적으로 _(언더바)를 작성해줍니다.
this.age 를 호출하면 get age() {} 가 호출되어 안에서 this.age를 사용하면 무한루프에 빠지기에 get age() {} 안에는 this._age 같이 언더바를 작성하여 무한루프를 방지할 수 있습니다.
3. Static properties and methods
클래스를 선언할때 프로퍼티와 메소드 앞에 static 키워드를 작성하여 선언한다.
class Article {
static publisher = "leo"
constructor(articleNumber) {
this.articleNumber = articleNumber
}
static printPublisher() {
console.log(Article.publisher)
}
}
console.log(Article.publisher) // leo
Article.printPbulisher() // leo
어떤 객체든 상관없이 공통된 모든 객체에 같은 프로퍼티, 메소드가 필요할 때 사용되면 메모리를 줄일수 있다.
static propery와 static method는 객체로 접근하여 사용할 수 없다. ( obj.property, obj.method)
클래스로만 접근하여 사용할 수 있다. (Class.property, Class.method)
4. 클래스 상속 (Inheritance)
클래스에서 다른 클래스를 상속하면서 클래스의 기능을 확장해 갈 수있다.
상속받을 클래스를 선언할 때 extends 부모클래스 키워드를 사용하여 선언한다.
class Shape {
constructor(width, height, color) {
this.width = width
this.height = heigth
this.color = color
}
draw() {
console.log(`drawing ${this.color} color of`)
}
getArea() {
return this.width * this.height
}
}
class Rectangle extends Shape {} // Shpae 클래스를 상속받아 사용한다. (밑 참조)
class Triangle extends Shape { // Shpae 클래스를 상속받아 오버라이딩 하여 사용할 수 있다.(밑 참조)
draw() {
super.draw() // super를 사용하여 부모클래스의 메소드도 호출하여 사용할 수 있다.(밑 참조)
console.log("🔺")
}
getArea() {
return (this.width * this.height) / 2
}
}
const rectangle = new Rectangle(20, 20, "blue")
rectangle.draw()
console.log(rectangle.getArea())
const triangle = new Triangle(20, 20, "red")
triangle.draw()
console.log(triangle.getArea())
- Rectangle 과 Triangle 클래스가 extends 를 사용하여 Shape클래스를 상속받는다.
- 상속 받을때 프로퍼티와 메소드는 오버라이딩이 가능하다.
- super 로 부모클래스의 메소드와 프로퍼티에 접근이 가능하다.
super - 부모 클래스로부터 상속받은 필드나 메소드를 자식 클래스에서 참조하는 데 사용하는 변수입니다.
오버라이딩 - 자식 클래스가 부모 클래스를 상속받으며 선언될 때, 부모클래스의 프로퍼티와 메소드를 재정의 한다.
결론
Class 를 이용할 경우 규칙성을 갖는 객체를 일관성 있게 만드는게 가능하며, 상속을 통해 기능 확장이 용이하다!
Reference
반응형