javascript-5: Class
Class
정의
- class: template
- object: instanc of a class
1. Class declarations
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
speak() {
console.log(`${this.name}: hello`);
}
}
const gido = new Person ('gido', 20);
console.log(gido.name);
console.log(gido.age);
gido.speak();
* Person이라는 class를 만들고, constructor(생성자)를 이용해 object를 만들때 필요한 데이터를 전달
* name, age라는 fields와 speak라는 methods 기입
* object를 만들때는 new를 붙여줘야함
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;
}
}
const user1 = new User('Steve','Job',-1);
console.log(user1.age);
* set은 값을 설정하기 때문에 value를 받아와야함
* get과 set에 쓰이는 변수 이름을 바꿔줘야함 (age → _age)
3. Fields (public, private)
class Experiment{
publicField = 2; // 외부에서 읽기,수정 가능
#privateField = 0; // 외부에서 읽기,수정 불가능
}
const experiment=newExperiment();
console.log(experiment.publicField);
console.log(experiment.privateField);
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();
* static은 class자체에만 있는 함수.
* static함수의 메서드를 호출하려면 class자체의메서드를 불러줘야함
5. Inheritance (상속)
- 상속 : extend로 연장하면 똑같은 클래스를 같이 쓸 수있음
- 다양성 : 필요한 함수만 재정의해서 쓸수있음. overwriting
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; //overwriting
}
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());
6. Class checking: instance Of
- 왼쪽이 오른쪽 클래스를 통해 만들어진 아이인지 아닌지 확인
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 : 모든 class들은 js의 object를 상속한것임
댓글남기기