Prototype

mamomi·2022년 10월 26일
0

practice-js

목록 보기
4/10
post-thumbnail

prototype으로 함수 여러 개 한 번에 선언, 할당해서 변수 한 번만 넣어도 되니까 진짜 편하다. 계속 편한 게 나오는 것이 아주 신기하네

1. 국어, 영어, 수학 점수를 생성자 파라미터로 입력받아서 합계와 평균을 구하는 클래스 Student를 작성하시오. 이 때 Student 클래스는 합계를 리턴하는 메서드인 sum()과 평균을 리턴하는 avg()를 제공합니다. 작성된 클래스를 활용하여 아래 표에 대한 학생별 합계 점수와 평균점수를 출력하시오. 클래스는 JSON 형식으로 작성되어야 합니다.

function Student(kor, eng, math) {
    this._kor = kor;
    this._eng = eng;
    this._math = math;
}

Student.prototype = {
    sum : function() {
        return this._kor + this._eng + this._math;
    },
    avg : function() {
        return this.sum() / 3;
    }
};

console.group("하드코딩");
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();

// 다른 방법
console.group("반복문 안에서 객체 활용");
const grade = [
    ["철수",92,81,77],
    ["영희",72,95,98],
    ["민혁",80,86,84]
];
for (const item of grade) {
    const s = new Student(item[1],item[2],item[3]);
    console.log("%s의 총점은 %d점이고 평균은 %d점 입니다.", item[0], s.sum(), s.avg());
}
console.groupEnd();

2. 가로(width), 세로(height)정보를 getter, setter로 관리하는 Rectangle 클래스를 정의하시오. 이 클래스는 생성자의 파라미터가 없으며 둘레의 길이를 구해 리턴하는 getAround() 메서드와 넓이를 구해 리턴하는 gerArea() 메서드를 제공합니다. 클래스는 JSON 형식으로 작성되어야 합니다.

function Rectangle(){
    this._width = null;
    this._height = null;
}

Rectangle.prototype = {
    get width () {
        return this._width;
    },
    set width (param) {
        this._width = param;
    },
    get height () {
        return this._height;
    },
    set height (param) {
        this._height = param;
    },
    getAround : function () {
        return this.width*2 + this.height*2; 
    },
    getArea : function () {
        return this.width*this.height;
    },
    result : function () {
        console.log("이 사각형의 둘레의 길이는 %d이고 넓이는 %d입니다.", this.getAround(), this.getArea());
    }
};
const a = new Rectangle();
a.width = 10;
a.height = 5;
a.result(); 

3. 다음을 만족하는 Student 클래스를 작성하시오.

1) String형의 학과와 정수형의 학번을 프로퍼티로 선언후 생성자를 통해 주입
2) getter, setter를 정의
3) sayHello() 메서드를 통해 "나는 OOOO학과 OO학번 입니다." 를 출력하는 기능을 구현하는 클래스 작성 후 아래의 소스를 실행하여 동일한 출력결과를 생성하시오.

function Student(departmentName, departmentNumber) {
    this._departmentName = departmentName;
    this._departmentNumber = departmentNumber;
}
Student.prototype = {
    // getter, setter를 정의
    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: function() {
        console.log(`나는 ${this.departmentName}학과 ${this.departmentNumber}학번입니다.`);
    }
};
const stud = new Student("컴퓨터", 202004123);
stud.sayHello();

4. 다음을 만족하는 클래스 Account를 작성하시오.

1) 다음의 2 개의 필드를 선언
문자열 owner; (이름)
숫자형 balance; (금액)
2) 위 모든 필드에 대한 getter와 setter의 구현
3) 위 모든 필드를 사용하는 가능한 모든 생성자의 구현
4) 메소드 deposit()의 헤드는 다음과 같으며 인자인 금액을 저축하는 메소드
deposit(amount)
5) 메소드 withdraw()의 헤드는 다음과 같으며 인자인 금액을 인출(리턴)하는 메소드 withdraw(long amount)
인출 상한 금액은 잔액까지로 하며, 이 경우 이러한 상황을 출력 클래스 작성 후 아래의 소스를 실행하여 동일한 출력결과를 생성하시오.

function Account(owner, balance) {
    // 다음의 2 개의 필드를 선언
    // - 문자열 owner; (이름)
    // - 숫자형 balance; (금액)
    this._owner = owner;
    this._balance = balance;
}
Account.prototype = {
    // 위 모든 필드에 대한 getter와 setter의 구현
    get owner() { return this._owner; },
    set owner(v) { this._owner = v; },
    get balance() { return this._balance; },
    set balance(v) { this._balance = v; },
    // 인자인 금액을 저축하는 메소드
    disposit: function(amount) {
        this.balance += amount;
    },
    withdraw: function(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);

profile
되고 싶다. 나는. 멋진 개발자가.

0개의 댓글

관련 채용 정보