💡 드림코딩님 자바스크립트 기초강의를 듣고 정리 및 공부
class Pesrson {
//constructor
constructor(name, age) {
//fields
this.name = name;
this.age = age;
}
//method
speak() {
console.log(`${this.name} : hello!`);
}
}
//object 생성
const jack = new Pesrson("jack", 20);
console.log(jack); // Pesrson {name: 'jack', age: 20}
jack.speak(); // jack : hello!
new 클래스이름
호출하면 객체가 생성된다.Constructor(생성자)
: object를 만들 data를 전달fields
: 전달된 data를 할당해 줌get
과set
을 붙여준다.class User {
constructor(firstName, LastName, age) {
this.firstName = firstName;
this.LastName = LastName;
this.age = age;
}
}
// 나쁜 예시
const badUser = new User("steve", "job", -1);
console.log(badUser.age); // 나이 -1살은 없다
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 } }
- getter과 setter를 정의하는 순간 this.age = value가 되고 무한 루프가 되어 error가 발생한다. 이를 막기 위해서는 프로퍼티의 이름이 중복되지 않게 변경해 주어야 한다.
get age() { return this._age; } set age(value) { this._age = value < 0 ? 0 : value; }
class Experiment {
publickField = 2;
#privateField = 0;
}
const experiment = new Experiment();
console.log(experiment.publickField); // 2
console.log(experiment.privateField); // undefined
public(공개)
property : 외부에서 접근 가능private(비공개)
property : class 내부에서만 사용함 외부에서는 불가능class Article {
// Static property
static publisher = "Coding";
constructor(articleNumber) {
this.articleNumber = articleNumber;
}
// Static method
static printPublisher() {
console.log(Article.publisher);
}
}
const article = new Article(1);
console.log(article.publisher); // undefined
console.log(Article.publisher); // Coding
Article.printPublisher(); // Coding
class 자식 클래스 extends 부모 클래스 {}
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, "blue");
console.log(rectangle.width); // 20
rectangle.draw(); // drawing blue color!
super
키워드를 통해 부모 클래스의 메소드를 그대로 가져올 수 있다.super.부모 프로퍼티
, super.부모 메서드
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 this.width * this.height;
}
}
class Triangle extends Shape {
draw() {
super.draw(); // 부모의 값을 그대로 가져올 수 있음
console.log("새로운 값");
}
getArea() {
return (this.width * this.height) / 2;
}
}
const triangle = new Triangle(20, 20, "red");
console.log(triangle.getArea()); // 200
console.log(triangle.draw()); // drawing red color! 새로운 값
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());