개인적인 생각으론,, 이런 경우가 있다. 함수에서 선언되지 않은 변수명을 사용할 경우 사용이 가능하다. 즉, 변수를 선언해주지 않아도 자동으로 전역변수로 선언이 되고 사용할 수 있게 된다. 때문에 메서드에서 this를 사용하지 않으면 선언되지 않은 변수라 생각하고 전역변수를 만드는 것 같다.
밑에 코드에서 this를 쓰지 않으면 오류가 난다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<title>함수</title>
<script>
function TestScore(name, kor, eng) {
this.userName = name;
this.korNum = kor;
this.engNum = eng;
}
TestScore.prototype.getTestInfo = function () {
document.write("이름: " + this.userName, "<br>");
document.write("국어: " + this.korNum, "<br>");
document.write("영어: " + this.engNum, "<br>");
};
TestScore.prototype.getAvg = function () {
return (this.korNum + this.engNum) / 2;
};
var kimgun = new TestScore("김군", 80, 90);
var ohgun = new TestScore("오군", 100, 80);
kimgun.getTestInfo();
document.write("평균 점수:" + kimgun.getAvg(), "<br><br>");
ohgun.getTestInfo();
document.write("평균 점수:" + ohgun.getAvg(), "<br>");
</script>
</head>
<body></body>
</html>