javaScript

프로토타입 방식 클래스

mooyou 2023. 6. 16. 22:58
728x90
300x250
SMALL

프로토타입 기반의 클래스는 생성자 함수와 프로토타입 객체를 사용하여 정의된다. 생성자 함수는 클래스의 초기화를 담당하고, 프로토타입 객체는 클래스의 메서드와 속성을 포함한다.

 

문법

function 클래스이름() {
    this.프로퍼티1=초깃값;
    this.프로퍼티2=초깃값;
    ...
}

클래스이름.prototype.메서드=function(){
   ...
}

프로퍼티 정의는 함수방식과 동일하게 this를 사용하고 메서드를 정의할때는 prototype이라는 프로퍼티에 정의 하는 구조이다.

 

프로토타입 클래스 예제

//생성자 함수
function Person(name, age) {
    this.name = name;
    this.age=age;
}

//프로토타입 메서드
Person.prototype.sayHello = function(){
    console.log("안녕하세요! 저는"+this.name+"입니다.");
};

Person.prototype.getAge=function(){
    return this.age;
}

//객체 인스턴스 생성
var person1 = new Person("John", 25);
var person2 = new Person("jane", 32);

//메서드 호출
person1.sayHello(); //안녕하세요! 저는John입니다.
console.log(person2.getAge()); //32

 

생성자 함수 정의 방법

생성자는 주로 프로퍼트 생성 및 객체 정보나 상태를 초기화 하는 메서드를 호출한다.

function 클래스이름(){
	초기화 작업
}

 

프로퍼티 정의 방법

function 클래스이름(){
    this.프로퍼티1 = 초깃값;
    this.프로퍼티2 = 초깃값;
}

 

메서드 정의 방법

클래스이름.prototype.메서드1=function(){};
클래스이름.prototype.메서드2=function(){};

 

인스턴스 생성 방법

var 인스턴스 = new 클래스이름();

 

객체 외부에서 프로퍼티와 메서드 접근방법

인스턴스.프로퍼티1;
인스턴스.메서드1();

 

객체 내부에서 프로퍼티와 메서드 접근 방법

function 클래스이름(){
	this.프로퍼티1 = 초깃값;
    this.프로퍼티2 = 초깃값;
}
클래스이름.prototype.메서드1=function(){
	alert(this.프로퍼티1);
    this.메서드2();
};
클래스이름.prototype.메서드2=function(){};
var 인스턴스 = new 클래스이름();
728x90
반응형
LIST