자바스크립트

자바스크립트_생성자함수

subdong7 2017. 1. 20. 21:47

● 생성자 함수

7장임다~


생성자 함수는 new 키워드로 객체를 생성할 수 있는 함수를 의미한다.

이전장에서 함수로 객체를 생성했지만, new 키워드를 사용하지 않았으므로 생성자 함수라고 부를 수 없다.



▶ 생성자 함수 만들기


function student () {

}


이렇게 생성한 생성자 함수는 new 키워드로 객체를 생성한다.


var student = new student();



● 생성자 함수의 이름

생성자 함수의 이름은 일반적으로 대문자로 시작한다.

대문자로 시작하지 않아도 문제 없지만 대부분의 개발자가 지키는 규칙이다.

자바스크립트에 기본적으로 있는 생성자 함수도 모두 대문자로 시작한다.


생성자 함수 안에서는 this 키워드로 생성자 함수로 생성될 객체의 속성을 지정한다.


 

▶ 속성 생성

 

function Student( name, korean, math, english, science ) {

this.이름 = name;

this.국어 = korean;

this.수학 = math;

this.영어 = english;

this.과학 = science;

 

}

 

var student = new Student( '홍길동', 90, 80, 87, 100 );

 

▶ 생성자 함수 안에 메서드를 만들어 본다.

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.toString = function () {

return this.이름 + '\t' + this.getSum() + this.getAverage();

};

 

}

 

var student = new Student( '홍길동', 90, 80, 87, 100 );

 

 

▶ 학생들의 총점과 평균을 구하는 예제

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.toString = function () {

return this.이름 + '\t' + this.getSum() + '\t' + this.getAverage();

};

 

 

}

 

var students = [];

students.push( new Student ( '홍길동', 100, 80, 60, 50 ) );

students.push( new Student ( '홍길순', 70, 80, 66, 80 ) );

 

var output = '이름 \t총점\t평균\n';

for ( var i in students ) {

output += students[i].toString() + '\n';

}

 

alert(output);

 

결과 :

 

 

 

 

 

출처 책 : 모던 웹을 위한 JavaScript jQuery 입문 by 윤인성