생성자함수
생성자 함수는 그냥 함수이다. 단 함수를 호출할 때 new를 붙여서 호출하면 생성자 함수로 호출이 된다.
생성자 함수로 사용할 함수의 함수명은 첫글자를 대문자로 쓰는 것이 관례이다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<style>
div {
background-color: skyblue;
height: 200px;
border: 1px solid;
}
</style>
<body>
<h2>생성자 함수</h2>
<div id="constructor-note"></div>
<script>
function Student(className,name,kor,eng,math){
let score = 100;
//생성자 함수로 생성할 객체의 속성을 정의하고, 해당 속성에 매개변수로 받아온 값을 할당
this.className = className;
this.name = name;
this.kor = kor;
this.eng = eng;
this.math = math;
//메소드 정의
this.getSum = function (){
return this.kor + this.eng + this.math;
}
this.getAvg = function (){
return this.getSum()/3;
}
this.toString = function (){
return `${this.className} /${this.name} / 총점 : ${this.getSum()} / 평균 : ${this.getAvg()}`
}
}
//일반 함수로 실행
let test = Student('classA','홍길동',100,100,100);
console.dir(test); // -> undefined
console.dir(window); // -> window의 속성에 Student 객체 속성들이 추가된 것을 확인할 수 있다.
document.querySelector('#constructor-note').innerHTML+=`${window.toString()}<br>`
// -> window속성에 있는 Student객체의 메소드인 toString()확인.
let student = new Student('classB','전우치',100,80,60);
console.dir(student); //->생성한 Student객체 student 출력
document.querySelector('#constructor-note').innerHTML+=`${student.toString()}<br>`
</script>
</body>
</html>