생성자 함수
생성자 함수는 new키워드로 객체를 생성할 수 있는 함수를 의미합니다. 객체를 생성할 때 사용하는 함수라고 생각하면 됩니다.
용어
- 인스턴스 : 생성자 함수를 기반으로 생성한 객체를 인스턴스라고합니다.
- 프로토타입 : 생성자 함수로 생성한 객체들이 공동으로 갖는 공간입니다. 일반적으로 메서드를 이러한 공간에 선언합니다.
생성자 함수 생성 형태
function Student() { }
이렇게 생성한 함수는 아래코드처럼 new키워드로 객체를 생성합니다.
객체 생성
function Student() { }
var student = new Student();
생성자 함수의 이름
생성자 함수의 이름은 일반저그올 대문자로 시작합니다. 대문자로 시작하지 않아도 문제는 없지만 개발자 대부분이 지키는 규칙이기 때문에 따르는 것이 좋습니다. 자바스크립트에서 기본적으로 제공하는 생성자 함수도 모두 대문자로 시작합니다.
생성자 함수 안에서는 this키워드를 통해 생성자 함수로 생성될 객체의 속성을 지정합니다.
속성 생성하기 예
function Student(name, korean, math, english, science, test) {
this.name = name;
this.korean = korean;
this.math = math;
this.english = english;
this.science = science;
this.테스트 = test;
}
var student = new Student('shiro', '국어', '수학', '영어', '과학', '테스트');
console.log(student);
/*
english: "영어"
korean: "국어"
math: "수학"
name: "shiro"
science: "과학"
테스트: "테스트"
*/
메서드 생성하기 예
function Student(name, korean, math, english, science, test) {
this.name = name;
this.korean = korean;
this.math = math;
this.english = english;
this.science = science;
this.테스트 = test;
// 메서드
this.getSum = function() {
return this.korean + this.math + this.english + this.science;
};
this.getAverage = function() {
return this.getSum() / 4;
};
this.toString = function() {
return this.name + '\t' + this.getSum() + '\t' + this.getAverage();
};
}
var student = new Student('shiro', 96, 98, 100, 100, '테스트입니다.');
console.log(student.getSum()); // 394
console.log(student.getAverage()); // 98.5
console.log(student.toString()); // shiro 394 98.5
메서드를 생성하는 방법도 속성을 만드는 방법과 같습니다. this키워드로 속성을 생성하고 함수를 넣어줍니다.
생성자 함수를 사용한 객체 배열 생성
function Student(name, korean, math, english, science) {
this.name = name;
this.korean = korean;
this.math = math;
this.english = english;
this.science = science;
// 메서드
this.getSum = function() {
return this.korean + this.math + this.english + this.science;
};
this.getAverage = function() {
return this.getSum() / 4;
};
this.toString = function() {
return this.name + '\t' + this.getSum() + '\t' + this.getAverage();
};
}
var students = [];
students.push(new Student('shiro', 98, 99, 100, 86));
students.push(new Student('AAA', 78, 66, 90, 100));
students.push(new Student('BBB', 67, 77, 70, 100));
students.push(new Student('CCC', 45, 88, 60, 66));
var output = '이름\t총점\t평균\n';
for(var i in students) {
output += students[i].toString() + '\n';
}
console.log(output);
/*
이름 총점 평균
shiro 383 95.75
AAA 334 83.5
BBB 314 78.5
CCC 259 64.75
*/
실행하면 각각 학생의 총점과 평균을 출력합니다.
용어 정리
Student()함수는 new키워드로 객체를 생성하므로 생성자 함수(constructor)입니다. 그리고 Student 생성자 함수로 만든 객체 student를 객체(Object)또는 인스턴스(Instance)라고 부릅니다.
'JavaScript | TypeScript > Javascript 시작하기' 카테고리의 다른 글
[ Javascript ] 캡슐화 (0) | 2022.06.14 |
---|---|
[ Javascript ] 프로토타입 (0) | 2022.06.13 |
[ Javascript ] 전개 연산자를 사용한 배열 테크닉, 배열 복제 (0) | 2022.06.13 |
[ Javascript ] 참조 복사와 값 복사 (0) | 2022.06.10 |
[ Javascript ] 함수를 사용한 객체 생성 (0) | 2022.06.10 |