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

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



<script type="text/javascript">

function makeStudent(name,kor, eng){

var willReturn = {

name : name,

kor : kor,

eng : eng,

//method

getSum:function(){

return this.kor + this.eng;

},

getAvg:function(){

return this.getSum() / 2;

},

toString : function(){

return this.name + '\t' + this.getSum() + '\t' + this.getAvg();

}

};

return willReturn;

}

var students = [];

students.push(makeStudent('john', 100, 100) );

students.push(makeStudent('tom', 100, 80) );

students.push(makeStudent('mike', 70, 100) );

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

for( var i in students ){

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

}

alert(output);

</script>

; 일반함수 와 동일하다. 


2. prototype

- 속성은 다른값을 가지지만 메서드는 동일하다. 객체를 생성할때마다 동일한 함수가 계속 생성될것이다.

100개 객체를 생성하면 100개의 동일한 메서드가 생성된다.( 메모리 비효율적 )

- 생성자함수를 통해서 생성된 객체가 가지는 공통 공간

  동일한 메서드는 프로토타입 공간으로 이동한다.

- 자바스크립트의 모든 함수는 prototype 객체를 가지고 있다. 


<script type="text/javascript">

function Student(name,kor, eng){

this.name = name;

this.kor = kor;
this.eng = eng;

}

Student.prototype.getSum = function(){

return this.kor + this.eng;

};

  Student.prototype.getAvg = function(){

   return this.getSum() / 2;

};

Student.prototype.toString = function(){

return this.name + '\t' + this.getSum() + '\t' + this.getAvg();

};


</script>




+ Recent posts