정골라코딩
[JavaScript] class 본문
문제 설명)
기존 자바스크립트 문법은 클래스 표현식이 없었지만 ES6는 클래스를 정의하여 사용할 수 있습니다.
class 키워드로 클래스를 정의할 수 있습니다. 클래스 내에 생성자(constructor())도 항상 포함되어 있어야 합니다. 클래스에 대한 자세한 내용은 링크에서 확인해보세요!
class ClassName {
constructor() { ... }
}
아래는 자동차의 이름과 연도에 대한 정보를 담는 클래스입니다.
class Car { constructor(name, year) {
this.name = name;
this.year = year;
}
}
클래스 객체 생성은 아래처럼 할 수 있습니다.
let myCar1 = new Car("Ford", 2014); l
et myCar2 = new Car("Audi", 2019);
생성한 객체의 요소들에 접근하여 출력할 수도 있습니다.
document.write(myCar1.name)
document.write(myCar1.year)
[지시사항]
square1 의 넓이와 suare2의 둘레를 구하시오.
square1 => width: 7, height: 9
square2 => width: 8, height: 10
class Square {
constructor(width, height) {
this.width = width; // this 목~금
this.height = height;
}
getArea() {
return this.width * this.height;
}
getRount() {
return 2 * (this.width + this.height);
}
}
let square1=new Square(7,9);
let square2= new Square(8,10);
document.write(square1.getArea());
document.write(square2.getRount());
'JavaScript > 연습문제' 카테고리의 다른 글
[JavaScript] map, filter, reduce 구현 (0) | 2022.09.29 |
---|---|
[JavaScript] this로 event 접근하기 (0) | 2022.09.29 |
[JavaScript] reduce() 함수 (0) | 2022.09.27 |
[JavaScript] map() 함수 (0) | 2022.09.27 |
[JavaScript] forEach() 함수 (0) | 2022.09.27 |