Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | 6 | |
7 | 8 | 9 | 10 | 11 | 12 | 13 |
14 | 15 | 16 | 17 | 18 | 19 | 20 |
21 | 22 | 23 | 24 | 25 | 26 | 27 |
28 | 29 | 30 | 31 |
Tags
- 가상메모리
- 힙
- dfs
- level0
- level3
- 구현
- 브루트포스
- MYSQL
- python
- level1
- 그리디
- N과M
- 재귀
- 딕셔너리
- dict
- 코딩테스트
- 다이나믹 프로그래밍
- 운영체제
- 다익스트라
- 수학
- level2
- BFS
- 가상메모리 관리
- 프로그래머스
- 백준
- 파이썬
- DP
- 스택
- programmers
- BOJ
Archives
- Today
- Total
동캄의 코딩도장
JS [Class] 본문
Class
-template
-declare once
-no data in
-틀
Object
- instance of a class
- created many times
- data in
'use strict'
// 1. Class declartions
class person{
//constructor
constructor(name,age){
//fields
this.name=name;
this.age=age;
}
// methods
speak(){
console.log(`${this.name}: hello!`);
}
}
const ellie = new person('ellie',20);
ellie.speak();
// 2. 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){
if (value<0){
value=0;
}
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);
// class 밖에서는 private에 접근 불가
// 최근에 나옴
// 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(Article.publisher);
Article.printPublisher();
// 들어오는 값에 상관없이 같은 내용을 출력할 때 사용
// 메모리 사용을 줄일 수 있음
// 5. 상속 & 다향성
// 공통적인 특성들을 클래스로 정리
class Shape{
constructor(width, height, color){
this.width=width;
this.height=height;
this.color=color;
}
draw(){
console.log(`drawing ${this.color} color of`);
}
getArea(){
return width * this.height;
}
}
class Rectangle extends Shape {}
class Triangle extends Shape{
draw(){
super.draw();
console.log('semo');
}
// 오버라이딩
getArea(){
return this.width * this.height /2;
}
}
const rectangle = new Rectangle(20,20,'blue');
rectangle.draw();
const triangle = new Triangle(20,20,'red');
triangle.draw();
console.log(triangle.getArea());
// 6. Class checking : instanceOf
// 왼쪽의 Object가 오른쪽의 class에 속하는지 확인
console.log(rectangle instanceof Rectangle);
'front > HTML&CSS&JS' 카테고리의 다른 글
JS [array] (0) | 2022.01.24 |
---|---|
JS [Object] (0) | 2022.01.24 |
JS [function] (0) | 2022.01.23 |
JS [operators] (0) | 2022.01.23 |
JS [variable] (0) | 2022.01.23 |