본문 바로가기

프로그래밍 공부/JavaScript

JavaScript - 생성자 함수

생성자 함수를 만드는 형태는 아래와 같다. Student 생성자 함수를 만드는 코드이다.

1
2
3
4
5
function Student(){
 
};
 
let student=new Student();
cs

위의 function Student(){}; 생성자 함수를 만들고 아래에 new 키워드를 입력해 객체를 생성할 수 있다. 생성자 함수의 이름은 일반적으로 대문자를 사용한다. 대문자로 시작하지 않아도 문제는 없다. 이후 this 키워드를 통해 생성자 함수로 생성될 객체의 속성을 지정하고 생성자 안에 메서드를 만들어서 넣을 수 있다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function Student(name, korean, math, english, science){
      this.이름=name;
      this.국어=korean;
      this.수학=math;
      this.영어=english;
      this.과학=science;
 
      this.getSum=function(){
          return this.국어+this.수학+this.영어+this.과학;
      };
      this.getAverage=function(){
          return this.getSum()/4;
      };
      this.result=function(){
          return this.이름+'\t'+this.getSum()+'\t'+this.getAverage();
      };
};
cs

그리고 아래에는 이전에 객체를 생성하는 함수와 마찬가지로 학생들의 정보 배열을 만들고 출력하는 프로세서 부분을 만들어주면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
let students = [];
students.push(new Student( '최ㅇㅇ'99929991 ));
students.push(new Student( '김ㅇㅇ'88889588 ));
students.push(new Student( '국ㅇㅇ'98789978 ));
students.push(new Student( '이ㅇㅇ'79959668 ));
students.push(new Student( '문ㅇㅇ'80968684 ));
students.push(new Student( '여ㅇㅇ'75799786 ));
students.push(new Student( '박ㅇㅇ'92948993 ));
students.push(new Student( '길ㅇㅇ'96886296 ));
students.push(new Student( '홍ㅇㅇ'95879985 ));
students.push(new Student( '연ㅇㅇ'95849177 ));
 
let summery='이름\t총점\t평균\n';
for(let i in students){
      summery+=students[i].result()+'\n';
}
console.log(summery);
cs

완성은 아래와 같다.

더보기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function Student(name, korean, math, english, science){
      this.이름=name;
      this.국어=korean;
      this.수학=math;
      this.영어=english;
      this.과학=science;
 
      this.getSum=function(){
          return this.국어+this.수학+this.영어+this.과학;
      };
      this.getAverage=function(){
          return this.getSum()/4;
      };
      this.result=function(){
          return this.이름+'\t'+this.getSum()+'\t'+this.getAverage();
      };
};        
 
let students = [];
students.push(new Student( '최ㅇㅇ'99929991 ));
students.push(new Student( '김ㅇㅇ'88889588 ));
students.push(new Student( '국ㅇㅇ'98789978 ));
students.push(new Student( '이ㅇㅇ'79959668 ));
students.push(new Student( '문ㅇㅇ'80968684 ));
students.push(new Student( '여ㅇㅇ'75799786 ));
students.push(new Student( '박ㅇㅇ'92948993 ));
students.push(new Student( '길ㅇㅇ'96886296 ));
students.push(new Student( '홍ㅇㅇ'95879985 ));
students.push(new Student( '연ㅇㅇ'95849177 ));        
 
let summery='이름\t총점\t평균\n';
for(let i in students){
      summery+=students[i].result()+'\n';
}
console.log(summery);
cs

형태는 이전에 배웠던 객체를 생성하는 함수와 비슷하다. 간단하게 정리하면 생성자 함수의 기본이되는 let student=new Student()를 보면 student부분이 객체, 인스턴트 부분이고, Student()가 생성자 함수 부분으로 정리할 수 있다.

다시 말하면 Student() 함수는 new 키워드로 객체를 생성함으로 생성자 함수(constructor)이고 Student() 생성자 함수로 만든 객체 student를 객체(object) 또는 인스턴스(instance)라고 부른다.

instanceof 키워드는 생성자 함수와 관련된 키워드이다. 이 키워드의 목적은 해당 객체가 어떠한 생성자 함수로 생성되었는지 확인할 때 사용된다. 따라서 위의 코드에 적용을 해서 student instanceof Student를 실행을 하게 되면 student 객체는 Student 생성자 함수의 인스턴트 이므로 true가 된다.

생성자 함수 연습

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
function Game(titel, type, language, price){
      this.제목=titel;
      this.장르=type;
      this.언어=language;
      this.가격=price;
 
      this.addtax=function(){
          return this.가격+this.가격*0.1;
      };
      this.viewall=function(){
          return this.제목+' \t'+this.장르+' \t'+this.언어+' \t'+this.addtax()+'\n';
      };
};
 
let games=[];
games.push(new Game('Call of Duty''FPS''Korean'110000));
games.push(new Game('Rainbow Six''FPS''Korean'55000));
games.push(new Game('Starcraft 2''RTS''Korean'33000));
games.push(new Game('Super Mario''RPG''Korean'78000));
games.push(new Game('Assasins Creed''RPG''Korean'65000));
games.push(new Game('Ghost Recon''RPG''Korean'120000));
 
let summery='제목\t\t\t장르\t언어\t가격\n';
for(let i in games){
      summery+=games[i].viewall();
}
console.log(summery);
cs

생성자 함수.html
0.00MB