- 속성(field), 행동(method) 이 종합적으로 묶여 있는 것
- 관련있는 함수나 변수를 묶어놓은 것
- 데이터가 들어있지 않고 틀(template)만 정의 > 한번만 선언한다.
- 클래스를 이용해서 데이터를 넣어서 새로운 instance을 만드는 것이 Object
class Person {
//constructor
constructor(name,age){
//fields
this.name = name;
this.age = age;
}
//medthods
speak(){
console.log(`${this.name}: hello!`);
}
}
const ellie = new Person(‘ellie’, 20);
console.log(ellie.name); // ellie
console.log(ellie.age); // 20
ellie.speak(); // ellie: hello!
1. Getter and Setter
: 방어적으로 사용할수 있게 만들어준다.
class User{
constructor(firstName, lastName, age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age() {
return this._age;
}
set age(value){
this._age = value < 0 ? 0 : value;
}
}
const user1 = new User(‘Steve’, ‘Job’, -1);
// 나이처럼 음수가 되면 않되는 값이 있을때 setter, getter를 사용할수 있다.
console.log(user1.age);
2. 상속과 다양성
class Shape {
constructor(width, height, color){
this.width = whidth;
this.height = height;
this.color = color;
}
draw() {
console.log(`drawing ${this.color} color!`);
}
getArea(){
return this.width = this.height;
}
}
class Rectangle extends Shape {}
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();
console.log(rectangle.getArea());
const triangle = new Triangle(20, 20, ‘red’);
triangle.draw();
console.log(triangle.getArea());
** 예제
class Counter {
constructor(runEveryTImes) {
this.counter = 0;
this.callback = runEveryTImes; // callback 사용
}
increase() {
this.counter++;
console.log(this.counter);
if (this.counter % 5 === 0) {
//printSomthing(this.counter); // 함수 실행
this.callback && this.callback(this.counter);
}
}
}
function printSomthing(num){ // 인자 이름은 알기쉽게 작성
console.log(`good ${num}`);
}
function alertNum(num) {
alert(`alert! ${num}`);
}
//const coolCounter = new Counter();
//coolCounter.increase(printSomthing); // 함수전달
const coolCounter = new Counter(printSomthing);
const alertCounter = new Counter(alertNum);
coolCounter.increase();
'Front > Javascript' 카테고리의 다른 글
Array (0) | 2024.02.17 |
---|---|
Object (0) | 2024.02.17 |
Function (0) | 2024.02.17 |
연산, 반복문 (0) | 2024.02.17 |
Deep Dive: 데이터 타입 (1) | 2023.12.20 |