class vs object
class | object |
연관있는 데이터들을 묶어 놓은 속성(field)과 행동(method)이 종합적으로 묶여있는 것 | 클래스를 이용해서 실제 데이터를 넣어서 만드는 것 |
붕어빵 틀 | 붕어빵 틀로 만드는 붕어빵 |
template | instance of a class |
declare once | created many times |
no data in | data in |
Javascript classes
- introduced in ES6
- syntactical sugar over prototype-based inheritance
1. Class declarations
class Person {
// constructor
constructor (name, age) {
// 속성(fields)
this.name = name;
this.age = age;
}
// 행동(method)
speak() {
console.log(`${this.name}: hello!`);
}
}
// Object 생성
const ellie = new Person('ellie', 20);
console.log(ellie.name); // ellie
console.log(ellie.age); // 20
ellie.speak(); // ellie: hello!
2. Getter and setters
class User {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
thie.age = age;
}
get age () {
return this._age; // 사용자가 입력한 값을 this._age로 받음
}
set age(value) {
this._age = value < 0 ? 0 : value; // 잘못된 값인지 확인해서 다시 설정해줌
}
}
const user1 = new User('Steve', Job', -1); // 나이는 음수가 될 수 없음
console.log(user1.age);
3. Fields (public, private)
- 최근에 추가되었기 때문에 아직 많이 사용하고 있지는 않음
class Experiment {
publicField = 2;
#privateField = 0; // 클래스 외부에서 보이지 않고, 읽을 수도 없음
}
const experiment = new Experiment();
console.log(experiment.publicField); // 2
console.log(experiment.privateField); // undefined
4. Static properties and methods
class Article {
static publisher = 'Dream Coding';
constructor(articleNumber) {
this.articleNumber = articleNumber;
}
static printPublisher() {
console.log(Article.publisher);
}
}
const article1 = new Article(1);
const article2 = new Article(2);
console.log(publisher); // undefined -> Article 클래스 내부에서 선언되었기 때문에 undefined가 출력됨
console.log(Article.publisher); // Dream Coding
Article.printPublisher(); // Dream Coding
5. Inheritance
- a way for one class to extend another class
class Shape {
constructor(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
}
draw() {
console.log(`drawing ${this.color} color!`);
}
getArea() {
return width * this.height;
}
}
class Rectangle extends Shape {} // extends 로 class 상속
class Triangle extends Shape {
draw() {
super.draw(); // 위에서 정의했던 부모 함수를 불러와서 출력하기
console.log('삼각형'); // 오버라이딩하면 부모 함수에서 정의했던 함수가 바뀌어서 출력됨
}
getArea() { // 오버라이딩: 필요한 함수를 다시 재정의하여 사용
return (this.width * this.height) / 2;
}
}
const rectangle = new Rectangle(20, 20, 'blue');
rectangle.draw(); // drawing blue color of
console.log(rectangle.getArea()); // 400
const triangle = new Rectangle(20, 20, 'red');
triangle.draw(); // drawing red color of
console.log(triangle.getArea()); // 200
6. Class cheking: instanceOf
- instanceOf 의 왼쪽에 있는 오브젝트가 오른쪽에 클래스의 인스턴스인지 확인하는 메서드
console.log(rectangle instanceOf Rectangle); // true
console.log(triangle instanceOf Rectangle); // false
console.log(triangle instanceOf Triangle); // true
console.log(triangle instanceOf Shape); // true
console.log(triangle instanceOf Object); // true
JavaScript reference (자바스크립트 object 참조)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
'JavaScript' 카테고리의 다른 글
Array (0) | 2023.06.12 |
---|---|
Object (1) | 2023.06.09 |
Function, Arrow Function (0) | 2023.06.07 |
operator, if, for loop (0) | 2023.06.05 |
variable, let vs var, hoisting, data types (0) | 2023.06.02 |