본문 바로가기

자바스크립트

JavaScript 클래스

 

 

 

 

클래스( class )란?

const neo = {
    name:'Neo',
    age: 22,
    getBirthYear(){
        const year=new Date().getFullYear()
        return year-this.age
    }
}

   - 변수와 메서드를 정의하여 모아놓은 하나의 틀입니다.

 

 

 

 

클래스의 활용

class User {
    constructor(name,age){
        this.name = name
        this.age = age
    }
    getBirthYear = function(){
        const year = new Date().getFullYear()
        return year-this.age
    }
}

const neo = new User('Neo',23)
const smith = new User('Smith',46)

console.log(neo)
console.log(smith)
console.log(neo.getBirthYear())
console.log(smith.getBirthYear())
console.log(neo.getBirthYear() === smith.getBirthYear())

   - 하나의 클래스를 만들어 여러개의 비슷한 데이터를 생성할 수 있습니다.

   - constructor(생성자)를 사용하여 클래스 생성 과정을 정의할 수 있습니다.

 

 

 

 

Getter & Setter

class User {
    constructor(name,age){
        this.name = name
        this.age = age
    }
    get userInfo(){
        return this.name+' '+this.age
    }
    set userInfo(value){
        const info = value.split(' ')
        this.name = info[0]
        this.age = info[1]
    }
}

const neo = new User('Neo','22')
neo.userInfo = 'Smith 46'

console.log(neo.userName)
console.log(neo)

   - 값을 불러오는 메서드를 Getter, 값을 변경하는 메서드를 Setter 라고 합니다.

실행화면

 

 

 

 

정적 메서드 ( static method )

const fruits = ['Apple','Banana','Cherry']

Array.prototype.abc = function(){
    console.log(this)
    return this.map(item=>item.slice(0,1).toLowerCase())
}

const newFruits = fruits.abc()

console.log(newFruits)

// Array.isArray 는 정적메서드입니다.
console.log(Array.isArray(fruits))
console.log(Array.isArray(newFruits))

// isArray는 인스턴스에서는 사용되지 않습니다 (에러발생)
console.log(fruits.isArray(newFruits))

   - 클래스 자체에서 호출되는 메서드로, 인스턴스와는 연결되지 않는 메서드입니다.

   - 주로 유틸리티함수를 만들 때 사용합니다.

실행결과

정적 메서드 만들기

class User {
    constructor(name,age){
        this.name = name
        this.age = age
    }
    static isUser(user){
        return user instanceof User
    }
}

const neo = new User('Neo', 28)
const smith = new User('Smith',46)
const jackson = {
    name: 'Jackson', 
    age: 37
}

console.log(User.isUser(neo), User.isUser(smith), User.isUser(jackson))
console.log(neo.isUser())

   - static 키워드를 활용하여 정적 메서드를 만들 수 있습니다.

실행 결과

 

 

 

 

클래스 상속 (class inheritance)

class A{
    constructor(a){
        this.a = a
    }
}

class B extends A {
    constructor(a,b){
        super(a)
        this.b = b
    }
}

const a = new A(1)
const b = new B(1,2)

console.log(a)
console.log(b)

console.log(a instanceof A)
console.log(b instanceof A)	// B는 A를 상속받으므로 true 입니다.

console.log(a instanceof B)
console.log(b instanceof B)

   - 하나의 클래스의 속성과 메서드를 다른 클래스에게 확장하여 재사용하는 기능입니다.

   - super 함수는 상속되는 클래스의 생성자를 호출하는데 사용됩니다.

   - 상속받는 클래스는 상속되는 클래스의 형태를 가지게 됩니다.

실행결과

'자바스크립트' 카테고리의 다른 글

JavaScript 비동기(2) - 콜백  (0) 2024.04.28
JavaScript 비동기(1) - 개요  (0) 2024.04.27
JavaScript 모듈  (0) 2024.04.26
JavaScript - 선택적 체이닝(Optional chaining)  (0) 2024.04.25
JavaScript 구조 분해 할당  (0) 2024.04.23