본문 바로가기

JavaScript

클래스와 인스턴스

자바스크립트에서도 클래스와 인스턴스가 있습니다

프로토타입을 이용한 객체지향 언어의 상속을 구현 할 수 있습니다

 

문법

ES5 문법에서는 프로토타입을 이용하여 구현 할 수 있고

ES6에서는 class라는 키워드를 통해서 구현 할 수 있습니다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// ES5 문법
const Student = (function () {
    //생성자 함수
    function Student(name) {
        this.name = name;
    }
    //프로토타입 메서드
    Student.prototype.printName = function () {
        console.log(this.name);
    };
    
    //정적 메서드
    Student.hello = function () {
        console.log(`Hello~ ${this.name}`);
    };
    return Student;
})();
 
// new  키워드로 인스턴스 생성
const person = new Student('Lee Joong Won');
 
person.printName();     // Lee Joong Won
person.hello();         // Error
 
Student.printName();    // Error
Student.hello();        // Hello~ Student
cs

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//ES6 문법
class Student {
    //생성자 함수
    constructor(name) {
        this.name = name;
    }
 
    //프로토타입 메서드
    printName() {
        console.log(this.name);
    }
 
    //정적 메서드
    static hello() {
        console.log(`Hello~ ${this.name}`);
    }
}
// new 키워드로 인스턴스 생성
const person = new Student('Lee Joong Won');
 
person.printName();     // Lee Joong Won
person.hello();         // Error
 
Student.printName();    // Error
Student.hello();        // Hello~ Student
cs

 

일반적으로 클래스이름은 파스칼 케이스를 사용합니다 (첫 글자가 대문자로 시작)

 

인스턴스

인스턴스를 생성하려면 new 키워드와 클래스를 가리키는 식별자로 선언합니다

( 변수 = new 클래스이름)

 

인스턴스의 this는 인스턴스를 가리키게 됩니다

(위의 코드에서 인스턴스 person의 this는 this = Student { name: 'Lee Joong Won' } 입니다)

인스턴스를 생성하고 person.printName()을 호출하면 this.name은 인스턴스를 찾아내며  인스턴스안의 name값을 찾아 Lee Joong Won 을 출력하게 됩니다

 

인스턴스를 생성하지 않고 this를 호출하게 된다면 클래스 자체를 가리키게 됩니다

(위의 코드에서 Student의 this는 this = [Function: Student] { hello: [Function (anonymous)] } 입니다)

인스턴스를 생성하지 않고  Student.hello() 를 호출하면 this는 클래스 Student를 찾아내며  클래스의 이름(name)을 찾아 Hello~ Student 을 출력하게 됩니다

 

 

'JavaScript' 카테고리의 다른 글

프로토타입  (0) 2022.09.21
객체지향 프로그래밍이란?  (1) 2022.09.21
함수란?  (0) 2022.09.20
변수와 타입  (0) 2022.09.20
JavaScript의 배열  (0) 2022.09.02