본문으로 바로가기

class

category JavaScript/ES6 2020. 11. 3. 04:00

class

동일한 종류의 객체를 여러개 생성해야 할 경우에는 생성자 함수를 이용했었다

ES6 이후에는 클래스 문법을 통해서 생성자 함수와 동일한 작업을 해줄 수 있는데

 class Student{
    ...
    ...
    }

const student1 = new Student(arg1,arg2);

객체를 생성하는 부분도 생성자 함수와 동일하다

new를 통해서 새로운 객체가 생성되고 인자들이 그 객체로 넘어간다

constructor

그 뒤 클래스 내부에 있는 constructor 메소드가 실행되며 객체가 초기화된다

그럼 Student 내부에 constructor메소드를 만들어주자

    class Student{
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }
    }

    const student1 = new Student('John',16);

이제 Student는 이름과 나이를 가진 객체를 생성하는 클래스가 되었다

method

이제 자기소개 메소드를 추가 해 보자

    class Student{
        constructor(name, age) {
            this.name = name;
            this.age = age;
        }

        introduce(){
            console.log('I\'m '+ this.name+' ' +this.age);
        }
    }

    const student1 = new Student('John',16);

getter, setter

자바스크립트의 클래스도 getter와 setter를 추가해 줄 수 있는데

        set name(name){
            this._name = name;
        }
        get name(){
            return this._name;
        }
        set age(age) {
            this._age = age;
        }
        get age(){
            return this._age;
        }

this._변수에서 _는 클래스 내부에서만 사용될 때 사용된다

를 추가해 주면 객체에서 프로퍼티에 접근할 때 처럼

student1.name = '아무개';
student1.age = 13;
console.log(student1.age)

로 접근이 가능해 진다

이렇게 게터 세터를 설정해 주었다면 내부 메소드인 introduce도

        introduce(){
            console.log('I\'m '+ this._name+' ' +this._age);
        }

로 바꿔주는 것이 옳다

프로퍼티

클래스에서 생성자 함수로 초기화된 변수들이나 메소드는 프로토타입에 정의되어있는 것을

클래스.prototype.변수, 클래스.prototype.메소드등의 코드로 확인해 볼 수 있다

프로퍼티로 추가한 값들은 프로토타입이 아닌 각 객체에서만 접근이 가능하다

    class Student{
        country = 'Korea';

        constructor(name, age) {
            this.name = name;
            this.age = age;
        }

이런 식으로 추가하게된 country는

Student.prototype.country로 접근시 undefined가 나온다

'JavaScript > ES6' 카테고리의 다른 글

promise  (0) 2020.11.03
arrow function  (0) 2020.10.26
Weakmap, Weakset  (0) 2020.10.25
Destructuring  (0) 2020.10.21
Array  (0) 2020.10.20