class object 객체지향
2021. 5. 17. 23:00ㆍTIL/자바스크립트
728x90
class는 붕어빵 틀이라면 object는 붕어빵 속(팥, 크림, 치즈..)
1. Class declaration
class Person {
// constructor
constructor(name, age) {
// fields
this.name = name;
this.age = age;
}
// methods
speak() {
console.log(`${this.name}: hello!`);
}
}
const bella = new Person('bella', 20);
console.log(bella.name);
console.log(bella.age);
bella.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) {
// throw Error('age can not be negative');
// }
this._age = value < 0 ? 0 : value;
}
}
const user1 = new User('Steve', 'Job', -1);
console.log(user1.age);
3. Fields (public, private)
private 변수는 함수 안에서만 읽어낼 수 있다
http://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference
class Experiment {
publicField = 2;
#privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publicField); //2
console.log(experiment.privateField); //undefined
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. Inheritance
class Shape {
constructor(width, height, color) {
this.width = width;
this.height = height;
this.color = color;
} //field
draw() {
console.log(`drawing ${this.color} color!`);
} //method
getArea() {
return this.width * this.height;
} //method
}
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());
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
'TIL > 자바스크립트' 카테고리의 다른 글
Array 배열 (0) | 2021.05.18 |
---|---|
Object (0) | 2021.05.18 |
Function 함수 (0) | 2021.05.14 |
자바스크립트 연산자, if문 for문 switch문 (0) | 2021.05.13 |
변수 var, let, const (0) | 2021.05.12 |