종우의 컴퓨터 공간

[ES6] Classes 본문

- 자바, 씨언어와 같은 오브젝트 오리엔티트 언어에서 사용하는 클래스와 신텍스가 비슷하다.

 

예제

class Person {
    constructor(firstName, lastName, dob) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.birthday = new Date(dob);
    }
    
    greeting() {
        return `Hello there ${this.firstName} ${this.lastName}`;
    }

    calculateAge() {
        const diff = Date.now() - this.birthday.getTime();
        const ageDate = new Date(diff);
        return Math.abs(ageDate.getUTCFullYear() - 1970);
    }

    getsMarried(newLastName) {
        this.lastName = newLastName;
    }

    //static method; for stand alone method which do not use any params
    static addNumbers(x, y) {
        return x + y;
    }
}

const mary = new Person('Mary', 'Williams', '06-09-1994');
mary.getsMarried('Smith');

console.log(mary);
console.log(mary.greeting());
console.log(mary.calculateAge());
console.log(mary.addNumbers(1, 2)); // yields TypeError: mary.addnumbers is not a function
console.log(Person.addNumbers(1, 2)); // need to use with the className not the instantiated object

- static method는 이 클래스의 필드를 사용하지 않고 stand alone 하는 느낌의 메소드 일 때 사용한다.

- static method는 객체를 instantiate 하지 않아도 사용할 수 있다.

- 그래서 오히려 객체에서 static method를 사용하려면 오류가 나고 클래스 이름 자체에서 메소드를 실행해야 한다.