프로토타입이랑 비슷한 거 같은데 참조하는 방식이 더 쉬웠다.
class Student {
kor;
eng;
math;
constructor(kor, eng, math) {
this.kor = kor;
this.eng = eng;
this.math = math;
}
sum() {
return this.kor + this.eng + this.math;
}
avg() {
return (this.kor + this.eng + this.math) / 3;
}
}
const s1 = new Student(92,81,77);
const s2 = new Student(72,95,98);
const s3 = new Student(80,86,84);
console.log("철수의 총점은 %d점이고 평균은 %d점 입니다.",s1.sum(),s1.avg());
console.log("영희 총점은 %d점이고 평균은 %d점 입니다.",s2.sum(),s2.avg());
console.log("민혁의 총점은 %d점이고 평균은 %d점 입니다.",s3.sum(),s3.avg());
console.groupEnd();
class Rectangle {
width;
height;
constructor(width,height) {
this.width = width;
this.height = height;
}
get width () {
return this.width;
}
set width (param) {
this.width = param;
}
get height () {
return this.height;
}
set height (param) {
this.height = param;
}
getAround () {
return this.width*2 + this.height*2;
}
getArea() {
return this.width*this.height;
}
result() {
console.log("이 사각형의 둘레의 길이는 %d이고 넓이는 %d입니다.", this.getAround(), this.getArea());
}
}
const wh1 = new Rectangle(10,5);
wh1.result();
1) String형의 학과와 정수형의 학번을 프로퍼티로 선언후 생성자를 통해 주입
2) getter, setter를 정의
3) sayHello() 메서드를 통해 "나는 OOOO학과 OO학번 입니다." 를 출력하는 기능을 구현하는 클래스 작성 후 아래의 소스를 실행하여 동일한 출력결과를 생성하시오.
class Student {
departmentName;
departmentNumber;
constructor(departmentName, departmentNumber) {
this.departmentName = departmentName;
this.departmentNumber = departmentNumber;
}
get departmentName() {
return this._departmentName;
}
set departmentName(departmentName) {
this._departmentName = departmentName;
}
get departmentNumber() {
return this._departmentNumber;
}
set departmentNumber(departmentNumber) {
this._departmentNumber = departmentNumber;
}
// sayHello() 메서드를 통해 "나는 OOOO학과 OO학번 입니다." 를 출력하는 기능을 구현
sayHello() {
console.log(`나는 ${this.departmentName}학과 ${this.departmentNumber}학번입니다.`);
}
}
const stud = new Student("컴퓨터", 202004123);
stud.sayHello();
1) 다음의 2 개의 필드를 선언
문자열 owner; (이름)
숫자형 balance; (금액)
2) 위 모든 필드에 대한 getter와 setter의 구현
3) 위 모든 필드를 사용하는 가능한 모든 생성자의 구현
4) 메소드 deposit()의 헤드는 다음과 같으며 인자인 금액을 저축하는 메소드 deposit(amount)
5) 메소드 withdraw()의 헤드는 다음과 같으며 인자인 금액을 인출(리턴)하는 메소드 withdraw(long amount)
인출 상한 금액은 잔액까지로 하며, 이 경우 이러한 상황을 출력 클래스 작성 후 아래의 소스를 실행하여 동일한 출력결과를 생성하시오.
class Account {
owner;
balance;
constructor(owner, balance) {
this.owner = owner;
this.balance = balance;
}
get owner() { return this._owner; }
set owner(v) { this._owner = v; }
get balance() { return this._balance; }
set balance(v) { this._balance = v; }
disposit(amount) {
this.balance += amount;
}
withdraw(amount) {
if (this.balance < amount) {
console.log("잔액이 부족합니다.");
return 0;
}
this.balance -= amount;
return amount;
}
}
const acc = new Account("Hello", 15000);
console.log("%s의 잔액은 %d원", acc.owner, acc.balance);
acc.disposit(5000);
console.log("%s의 잔액은 %d원", acc.owner, acc.balance);
acc.withdraw(15000);
console.log("%s의 잔액은 %d원", acc.owner, acc.balance);
acc.disposit(5000);
console.log("%s의 잔액은 %d원", acc.owner, acc.balance);
acc.withdraw(15000);
console.log("%s의 잔액은 %d원", acc.owner, acc.balance);
1) 자료를 저장하기 위한 배열인 data와 배열의 원소 수를 카운트 하기 위한 size라는 멤버변수를 은닉된 형태로 선언한다.
2) 생성자에서는 data를 원소가 0개인 빈 배열로, size는 0으로 초기화 한다.
3) data와 size에 대한 getter는 갖지만 setter는 갖지 않는다.
4) push(item) 메서드는 파라미터로 전달된 값을 배열의 맨 뒤에 추가하고 size의 값을 1 증가시킨다.
5) pop() 메서드는 배열의 마지막 원소를 꺼내어 리턴하고 배열의 크기를 1 축소시킨다.
6) 완성된 클래스는 아래의 테스트 코드를 사용하여 결과를 확인하시오.
class MyList {
#data;
#size;
constructor() {
this.#data = [];
this.#size = 0;
}
get data() {
return this.#data;
}
get size() {
return this.#size;
}
push(item) {
this.#data[this.#size] = item;
this.#size++;
// -> 간단하게 this.#data[this.#size++] = item;
}
pop() {
// 배열의 마지막 원소 꺼내기
const last = this.#data[this.#size-1];
// 임시변수에 깊은복사
const temp = new Array(this.#size);
for (let i=0; i<this.#size; i++) {
temp[i] = this.#data[i];
}
// 마지막 원소 제외하고 다시 data에 깊은 복사
this.#data = new Array(this.#size-1);
for (let i=0; i<this.#size-1; i++) {
this.#data[i] = temp[i];
}
// 배열의 크기를 1 축소
this.#size--;
return last;
}
}
const list = new MyList();
list.push(100);
list.push(200);
list.push(300);
console.log('원소의 수: %d, 데이터 확인: %s', list.size, list.data);
const x = list.pop();
console.log('추출된 데이터: %d', x);
console.log('원소의 수: %d, 데이터 확인: %s', list.size, list.data);
list.push(400);
list.push(500);
console.log('원소의 수: %d, 데이터 확인: %s', list.size, list.data);
const y = list.pop();
console.log('추출된 데이터: %d', y);
console.log('원소의 수: %d, 데이터 확인: %s', list.size, list.data);
list.push(600);
console.log('원소의 수: %d, 데이터 확인: %s', list.size, list.data);
const z = list.pop();
console.log('추출된 데이터: %d', z);
console.log('원소의 수: %d, 데이터 확인: %s', list.size, list.data);
1) 문제05에서 구현한 MyList 클래스를 문제06에 동일하게 복사하고 shift() 메서드와 unshift(item) 메서드를 추가한다.
2) shift() 메서드는 배열의 가장 첫 번째 원소를 꺼내어 리턴하고 배열의 크기를 1축소 시킨다.
3) unshift(item) 메서드는 파라미터로 전달된 값을 data의 맨 첫 번째 원소로 추가하고 기존의 데이터들은 한 칸씩 뒤로 밀어낸다.
4) 완성된 클래스는 아래의 테스트 코드를 사용하여 결과를 확인하시오.
class MyList {
#data;
#size;
constructor() {
this.#data = [];
this.#size = 0;
}
get data() {
return this.#data;
}
get size() {
return this.#size;
}
push(item) {
this.#data[this.#size] = item;
this.#size++;
// -> 간단하게 this.#data[this.#size++] = item;
}
pop() {
// 배열의 마지막 원소 꺼내기
const last = this.#data[this.#size-1];
// 임시변수에 깊은복사
const temp = new Array(this.#size);
for (let i=0; i<this.#size; i++) {
temp[i] = this.#data[i];
}
// 마지막 원소 제외하고 다시 data에 깊은 복사
this.#data = new Array(this.#size-1);
for (let i=0; i<this.#size-1; i++) {
this.#data[i] = temp[i];
}
// 배열의 크기를 1 축소
this.#size--;
return last;
}
shift() {
const first = this.#data[0];
// 임시변수를 data의 길이보다 1 작은 크기로 초기화하고 data의 1번째 원소부터 나머지 원소들을 임시변수에 깊은 복사
const tmp = new Array(this.#size-1);
for (let i=0; i<this.#size-1; i++) {
tmp[i] = this.#data[i+1];
}
// 복사가 완료되면 data의 크기를 기존보다 1 작게 다시 초기화하고 임시변수의 항목들을 그대로 깊은 복사
this.#data = new Array(this.#size-1);
for (let i=0; i<this.#size-1; i++) {
this.#data[i] = tmp[i];
}
this.#size--;
return first;
}
unshift(item) {
const tmp = new Array(this.#size);
for (let i=0; i<this.#size; i++) {
tmp[i] = this.#data[i];
}
this.#data = new Array(this.#size+1);
this.#data[0] = item;
for (let i=1; i<this.#size+1; i++) {
this.#data[i] = tmp[i-1];
}
this.#size++;
}
}
const list = new MyList();
list.push(100);
list.push(200);
list.push(300);
console.log('원소의 수: %d, 데이터 확인: %s', list.size, list.data);
const x = list.shift();
console.log('추출된 데이터: %d', x);
console.log('원소의 수: %d, 데이터 확인: %s', list.size, list.data);
list.push(400);
list.push(500);
console.log('원소의 수: %d, 데이터 확인: %s', list.size, list.data);
const y = list.shift();
console.log('추출된 데이터: %d', y);
console.log('원소의 수: %d, 데이터 확인: %s', list.size, list.data);
list.push(600);
console.log('원소의 수: %d, 데이터 확인: %s', list.size, list.data);
const z = list.shift();
console.log('추출된 데이터: %d', z);
console.log('원소의 수: %d, 데이터 확인: %s', list.size, list.data);
list.unshift(700);
console.log('원소의 수: %d, 데이터 확인: %s', list.size, list.data);
list.unshift(800);
list.unshift(900);
console.log('원소의 수: %d, 데이터 확인: %s', list.size, list.data);