티스토리 뷰
class & object
- class : template, declare one, no data in
- object : instance of a class, created many times, data in
class는 template에 속하고, 이 template을 이용해 실제로 데이터를 넣어서 만든 것이 object 이다.
javascript에 class는 ES6에 도입된 개념이다.
그럼 그 전까지는 어떻게 사용했을까?
class가 도입되기 전까지는 class를 정의하지 않고, 바로 object를 만들 수 있었다.
그리고 object를 만들 때 function을 이용하여 template을 만드는 방법이 있었다.
1. Class decalration
class Person {
//constructor
constructor(name, age) {
//fields
this.name = name;
this.age = age;
}
speak() {
console.log(`${this.name}: hello!`);
}
}
// new : 생성자 함수
const amy = new Person("amy", 20);
console.log(amy.name);
amy.getInfo();
this
일반(Normal) 함수는 호출된 위치에서 정의
화살표(Arrow) 함수는 자신이 선언된 함수 범위에서 this 정의
const amy = {
name: "amy",
normal: function () {
console.log(`normal ${this.name}`);
},
arrow: () => {
console.log(`arrow ${this.name}`); // 여기서 this 정의 -> 그러므로 undefined
},
};
amy.normal(); //여기서 this 정의
amy.arrow();
const timer = {
name: "amy",
timeout: function () {
setTimeout(() => {
console.log(this.name);
}, 2000);
},
};
timer.timeout();
2. Getters & Setters
*Getter & Setter 내의 변수명은 다르게 해줘야 함. 아니면 getter 와 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 : value1;
}
}
3. 상속
class Shape {
constructor(width, height, color ) {
this.width = width;
this.height = height;
this.color = color;
}
draw() {
console.log(`drawing ${this.color} color!!!`)
}
getArea() {
return this.width * this.height;
}
}
class Rectangle extends Shape {}
const rectangle = new Rectangle(20, 20, 'red');
rectangle.draw();
console.log(rectangle.getArea());
class Triangle extends Shape {
draw() {
super.draw();
console.log('⚠️');
}
getArea() {
return (this.width * this.height) / 2 ;
}
toString() {
return `Triangle: color ${this.color}`;
}
}
const triangle = new Triangle(20, 20, 'yellow');
triangle.draw();
console.log(triangle.getArea());
console.log(triangle.toString());
// Class checking: 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 - JavaScript | MDN
This part of the JavaScript section on MDN serves as a repository of facts about the JavaScript language. Read more about this reference.
developer.mozilla.org
'Javascript' 카테고리의 다른 글
| Javascript - 배열 (0) | 2021.09.03 |
|---|---|
| Javascript - Object (0) | 2021.09.02 |
| Javascript- 함수 선언 vs 함수 표현식 (0) | 2021.09.02 |
| Javascript - Callback function, First-Class function (0) | 2021.09.01 |
| Javascript - function, parameter (0) | 2021.09.01 |