JAVACSCRIPT

[js]생성자 함수(Constructor function)와 프로토타입 메서드(prototype method)

라텐느 2024. 9. 18. 14:23
반응형

생성자 함수(Constructor function)

:같은 유형의 객체를 여러개 생성할 때 사용하며 함수명의 첫글자는 대문자를 사용한다. 그리고 new 키워드를 통해 호출된다.

이때, 프로토타입을 통해 속성과 메서드를 추가시키고 상속할 수 있다. 

예제1

function Employee(num, name, email, sal, comm, deptid) {
		this.num = num;
		this.name = name;
		this.email = email;
		this.sal = sal;
		this.comm = comm;
		this.deptid = deptid;
	}

기본 생성자 함수 Employee

Employee.prototype.getYearSal = function() {
    let yearSal = this.sal * 12 + this.comm;
    return yearSal;
}

연봉을 계산하는 프로토타입 메서드

Employee.prototype.getDeptName = function() {
    let map = new Map();
    map.set(10, '인사');
    map.set(20, '자재');
    map.set(30, '연구개발');
    map.set(40, '총무');
    map.set(50, '생산');
    map.set(60, '관리');
    return map.get(this.deptid);
}

부서번호에 해당하는 부서명을 반환한느 프로토 타입 메서드

이때 java에서와 는 달리 map.put대신 map.set을 사용한다.

Employee.prototype.toString = function() {
    let html = `<ul class="box">`;
    html += `<li>직원번호:${this.num}</li>`;
    html += `<li>직원이름:${this.name}</li>`;
    html += `<li>이메일:${this.email}</li>`;
    html += `<li>월급:${this.sal}</li>`;
    html += `<li>연봉:${this.getYearSal()}</li>`;
    html += `<li>부서명:${this.getDeptName()}</li>`;
    html += `</ul>`;
    html += '<br>';
    return html;
}

직원 정보를 HTML 형식으로 반환하는 프로토타입 메서드. 직원 번호, 이름, 이메일, 월급, 연봉, 부서명을 포함한다.

let empList = [];
		//input
		//    num,  	name, 	email,	 sal, 	comm, 	deptid
		empList.push(new Employee(1, '가나', 'kana@naver.com', 230, 50, 10));
		empList.push(new Employee(2, '나나', 'nana@naver.com', 231, 0, 20));
		empList.push(new Employee(3, '다나', 'dana@naver.com', 232, 124, 30));
		empList.push(new Employee(4, '라나', 'rana@naver.com', 233, 23, 40));
		empList.push(new Employee(5, '마나', 'mana@naver.com', 234, 11, 50));
		empList.push(new Employee(6, '사나', 'sana@naver.com', 235, 24, 60));
		empList.push(new Employee(7, '바나', 'bana@naver.com', 236, 43, 20));

new키워드를 통해 Employee생성자 함수를 호출해서 empList배열에 삽입한다.

const div1El = document.getElementById('div1');
let html = '';
empList.forEach(function(emp, i) {
    html += emp.toString();
});
div1El.innerHTML = html;

forEach 메서드를 통해 각 배열을 할당을 하고 divEl을 HTML형식으로 담는다.


예제2

function Member(name, email, tel, birth) {
    this.name = name;
    this.email = email;
    this.tel = tel;
    this.birth = birth;
}

생성자함수 Member를 생성한다.

Member.prototype.getAge = function() {
    let thisYear = 2024;
    let birthYear = parseInt(this.birth.substring(0, 4)); // 생년 추출
    let age = thisYear - birthYear;
    return age;
}

나이를 계산하는 프로토타입 메서드

window.onload = function() {
    const nameEl = document.getElementById('name');
    const emailEl = document.getElementById('email');
    const telEl = document.getElementById('tel');
    const birthEl = document.getElementById('birth');
    const btnAddEl = document.getElementById('btnAdd');
    const listEl = document.getElementById('list');
	btnAddEl.onclick = function() {
    	let html = '';
    	let name = nameEl.value;
    	let email = emailEl.value;
    	let tel = telEl.value;
    	let birth = birthEl.value;
    
    	let member = new Member(name, email, tel, birth);
    	html = member.toString();
    	listEl.innerHTML += html;
	}
}

inputype속성의 id를 호출하여 Member함수에 상속시키고 문자열 형식으로 list테이블 안에HTML형태로 출력한다.

반응형