JavaScript 클래스 정의 방법 비교

2019. 9. 14. 16:51Web

1. 리터럴 방식

- 클래스 만드는 용도가 아니며 주로 여러 개의 매개변수를 그룹으로 묶어 함수의 매개변수로 보낼 때 사용

- 정의와 함께 인스턴스가 만들어지는 장점이 있음.

- 단, 인스턴스는 오직 하나만 만들 수 있음(재사용 X)

var NameOfInstance = {
    property1: initialValue,
    property2: initialValue, 
    
    method1: function() {
    
    }
    
    method2: function() {
    
    }
}

 

2. 함수 방식

- 간단한 클래스 제작 시 사용

- 인스턴스마다 메서드가 독립적으로 만들어지는 단점이 있음

function NameOfClass() {
    this.property1 = initialValue;
    this.property2 = initialValue;
    
    this.method1 = function() {
    
    }
    
    this.method2 = function() {
    
    }
 }

 

3. 프로토타입 방식

- 일반적인 클래스 제작 방법

- 인스턴스마다 공통된 메서드를 공유해서 사용하는 장점이 있음(함수 방식의 단점 극복)

function NameOfClass() {
    this.property1 = initialValue;
    this.property2 = initialValue;
}

NameOfClass.prototype.method1 = function() {

}

NameOfClass.prototype.method2 = function() {

}

'Web' 카테고리의 다른 글

[WEB]이미지 애니메이션 뷰어 제작  (0) 2019.09.08
[WEB] 텍스트 스크롤러 만들기  (0) 2019.09.07
HTML <style type = "text/css"> 의문점  (0) 2019.08.07