Class
[class]
- template, 청사진, 붕어빵 틀
- declare once
- no data in
[object]
- instance of a class, 클래스에 데이터를 넣어서 만드는 것, 팥붕어빵,슈붕어빵
- created many times
- data in
[Class declaration]
'use strict';
// Object-oriendted programming
// class: template
// object: instance of a class
// 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;
}
// methods
speak() {
console.log(`${this.name}: hello!`);
}
}
//object 생성
const ellie = new Person('ellie', 20);
console.log(ellie.name);
console.log(ellie.age);
ellie.speak();
[Getter and Setter]
- constructor에서의 this.age를 getter,setter에서 사용할 수 없는 이유는
- this.age(getter) = age(setter)로 각각 역할을 담당한다.
- setter에서 this.age를 사용할 경우 또다시 setter 를 돌게 되어 에러발생.....!
// 2. Getter and setters
class User {
constructor(firstName, lastName, age) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
get age() {
return this._age; //변수 이름을 다르게
}
set age(value) {
// if (value < 0) {
// throw Error('age can not be negative');
// }
this._age = value < 0 ? 0 : value;
//변수 이름을 조금 다르게 this.age로 할경우 계속해서 set을 돈다.
}
}
[Fields(public, private)]
- 최근에 추가된 것이라 지금 쓰기엔 이른 기술
- privateField는 클래스 안쪽에서만 rw가능, 밖에서는 불가능
// 3. Fields (public, private)
// Too soon!
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/Class_fields
class Experiment {
publicField = 2;
#privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publicField);
console.log(experiment.privateField);
[Static properties and methods]
- static이 붙은 것은 클래스 자체의 고유값이라 object.publisher하면 undefined가 뜬다
- object에 상관없이 들어오는 데이터에 상관없이 공통적으로 class에서 사용할 수 있는 경우 static 사용
// 4. Static properties and methods
// Too soon!
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(Article.publisher);
Article.printPublisher();
[Inheritance]
- Triangle 함수에서 오버라이딩을 통해 함수 재정의
// 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 this.width * this.height;
}
}
class Rectangle extends Shape {}
class Triangle extends Shape {
draw() {
super.draw();
console.log('🔺');
}
getArea() {
return (this.width * this.height) / 2;
}
toString() {
return `Triangle: color: ${this.color}`;
}
}
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 checking : instanceOf]
- 왼쪽 object가 오른쪽의 class인지 아닌지 확인
// 6. 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
console.log(triangle.toString()); //Triangle : color : red
let obj = { value: 5 };
function change(value) {
value.value = 7;
}
change(obj);
console.log(obj); // value : 7
유용한 사이트
JavaSCript reference들
https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference
JavaScript 참고서 - JavaScript | MDN
이 페이지는 JavaScript 언어에 대한 정보 보관소입니다. 이 참고서에 대해 더 읽어보세요.
developer.mozilla.org
- Value properties
- Error objects
- Indexed collections
- Keyed collections
- Promise
- JSON
Thanks for 드림코딩
'Front-end > Web' 카테고리의 다른 글
[JS] 배열 개념과 APIs 총정리 (0) | 2021.08.27 |
---|---|
[JS] 오브젝트 (0) | 2021.08.27 |
[JS] Arrow Function, 함수의 선언과 표현 (0) | 2021.08.27 |
[JS] operator, if, for loop 코드리뷰 팁 (0) | 2021.08.27 |
[JS] data types, let vs var, hoisting (0) | 2021.08.26 |
댓글