JavaScript - prototype

yeong ·2022년 11월 17일

js

목록 보기
22/49

프로토타입 메소드(Prototype Method)

클래스 함수를 이용하여 객체를 생성할 경우 : 클래스 함수에 선언된 프로퍼티와 메소드가 객체의 요소로 생성

프로퍼티는 객체의 속성값을 저장하기 위해 객체마다 따로 생성되어 사용히는 것이 맞지만 메소드는 동일한 명령의 함수가 객체마다 따로 생성되어 저장되는 것은 비효율적인 방법

객체의 메소드를 프로토타입 메소드로 선언하면 객체의 갯수에 상관없이 메소드가 하나만 생성되어 모든 객체가 공유하여 사용 가능

프로토타입 메소드 선언하기

클래스 함수에는 프로퍼티만 선언

	function Student(num,name,address) {
		this.num=num;
		this.name=name;
		this.address=address;
	}

클래스 함수에 프로토타입 메소드 추가

=> 객체에 상관없이 메모리(Method 영역)에 하나만 생성되어 모든 객체가 공유하여 사용

	Student.prototype.display=function() {
		alert("학번 = "+this.num+", 이름 = "+this.name+", 주소 = "+this.address);
	}
	Student.prototype.setValue=function(num,name,address) {
		this.num=num;
		this.name=name;
		this.address=address;
	}

프로토타입 메소드의 효율적인 관리를 위해 Object 객체({})의 요소로 메소드 선언

// !클래스 함수에는 프로퍼티만 선언
	Student.prototype={
		"display":function() {
			alert("학번 = "+this.num+", 이름 = "+this.name+", 주소 = "+this.address);
		},
		"setValue":function(num,name,address) {
			this.num=num;
			this.name=name;
			this.address=address;
		}
	}

> instanceof 연산자 : 변수에 저장된 객체가 클래스 함수로 생성되었는지를 비교하여 다른 경우 false를 제공하고 같은 경우 true 제공 - ES6에서 추가된 연산자
형식)객체변수 instanceof 클래스함수

alert(student instanceof Student);//true

in 연산자 : 객체의 요소를 확인하기 위한 연산자
형식)"요소명" in 객체 - 객체에 요소가 없는 경우 false를 반환하고 있는 경우 true를 반환

alert("num" in student);//true
alert("display" in student);//true
alert("phone" in student);//false

for 구문을 이용하여 객체 요소에 대한 일괄처리 가능
형식)for(변수 in 객체) { 명령; 명령; ... }
=> 객체에 저장된 요소명을 하나씩 제공받아 변수에 저장하여 반복 처리

for(variable in student) {
		//alert(variable);
		//요소의 이름을 제공받아 객체 요소를 사용하기 위해 . 연산자 대신 [] 연산자 이용
		if(typeof(student[variable])!="function") {//객체의 요소가 메소드가 아닌 경우
			alert("객체의 속성값 = "+student[variable]);
		}
	}

with 구문을 이용하여 객체 요소를 변수처럼 사용하는 기능 제공
형식)with(객체) { 명령; 명령; ... }

	with(student) {
		alert("학번 = "+num+", 이름 = "+name+", 주소 = "+address);
	}

0개의 댓글