Frontend/JS

function & class 학습응용

AIHYEONJI 2025. 4. 23. 21:04
// 하나의 로직을 수행하는 동작의 묶음
// 데이터를 저장하지 않고 실행만 함
function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function () {
    console.log(`안녕하세요, 저는 ${this.name}입니다.`);
  };
}

// 데이터 + 메서드를 하나의 틀로 묶은 설계도 객체를 만들 수 있음
// 객체를 만들 수 있음.
const p1 = new Person("이메론", 30);
p1.greet();

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
  greet() {
    console.log(`안녕하세요,${this.name}입니다.`);
  }
}

const P1 = new Person("김사과", 20);
P1.greet()
const P2 = new Person("반하나", 25);
P2.greet()

 

# function 과 class의 기능 차이는 뭘까?

=> 예를들면 function은 버튼 클릭 시 알림 띄우기  // class는 사용자, 게임 캐릭터, 쇼핑카트 처럼 상태를 가지게 하는 객체(ex. 장바구니에 목록 담기)

 

class Animal {
  constructor(name) {
    this.name = name;
  }
}

class Dog extends Animal {
    constructor(name,color){
        super(name)
        this.color = color
    }
    showInfo(){
        console.log(`${this.name}${this.color} 강아지입니다.`)
    }
}

const dog = new Dog('루시','흰색')
dog.showInfo()

console.log('--------------------------')

class Mathtool{
    constructor(num1,num2){
        this.num1=num1
        this.num2 = num2
    }
    static add(a,b){
        return a+b
    }
    subtract(){
        return this.num1-this.num2
    }
}

console.log('--------------------------')

class Product {
    name = "상품명 없음"
    price = 0
    static productName="컴퓨터"
    static productPrice="1,000,000원"

    showInfo(){
        console.log(`${this.name}의 가격은 ${this.price}원입니다.`)
    }
    static showStaticInfo(){
        console.log(`${this.productName}의 가격은 ${this.productPrice}원 입니다.`)
    }
}

const p = new Product()
p.showInfo()
Product.showStaticInfo()

 

get 과 set 이용

class User {
  constructor(name) {
    this._name = name;
  }
  get name() {
    console.log("값 읽는 중");
    return this._name;
  }

  set name(newName) {
    if (newName.length < 2) {
      console.log("이름은 두글자 이상 넣어야합니다.");
      return;
    }
    console.log("값 바꾸는 중..");
    this._name = newName;
  }
}
const user = new User("현지");

console.log(user.name); // getter 호출 -> 값을 읽는 중..
user.name = "김"; // setter 호출 -> 이름은 두글자 이상 넣어야합니다.
user.name = "김민지"; // setter 호출 -> 값을 바꾸는 중..
console.log(user.name); // 김민지
class Account {
    static accountCount = 0
    #balance = 0

    constructor(owner){
        this.owner = owner
        Account.accountCount++
    }
    get balane(){
        return this.#balance
    }
    set balance(value){
        console.log("직접 잔액을 설정할 수 없습니다.")
    }

    // 입금
    deposit(amount){
        if(amount >0){
            this.#balance += amount
            console.log(`${this.owner}${amount}원 입금되었습니다.`)
        }
    }
    // 출금
    withdraw(amount){
        if(amount <= this.balance){
            this.#balance -= amount
            console.log(`${this.owner}${amount}원 출금되었습니다.`)
        }else {
            console.log('잔액이 부족합니다.')
        }
    }
    static getAccountCount(){
        return `총 계좌수 : ${Account.accountCount}`
    }
}

const a1 = new Account("김사과");
a1.deposit(1000);
console.log(a1.balance); //getter의 balance 보는 방법
a1.balance = 5000; // setter 발동(잔액 설정을 임의대로 못하게)

a1.withdraw(300);

const a2 = new Account("반하나");
a2.deposit(2000);
console.log(a2.balance);

console.log(Account.getAccountCount());

'Frontend > JS' 카테고리의 다른 글

내장 객체 응용학습  (0) 2025.04.23
for문을 이용한 응용  (0) 2025.04.23
JS_조건문  (0) 2025.04.10
JS_연산자  (0) 2025.04.10
JS_변수형  (0) 2025.04.09