2014-04-25 2 views
0

다음 코드와 붙어있어 :프로토 타입 방법 "X는 정의되지 않는다"

나는 다음과 같은 코드가

이 실행시

function Calendar() { 
     this.month = "January"; 
    } 
    Calendar.prototype.getMonth = function() { 
     alert(cal.month); 
    } 
    $(document).ready(function() { 
     var cal = new Calendar(); 
     var div_cal = document.getElementById("div_cal"); 
     var div_controls = document.getElementById("div_controls"); 
     div_controls.innerHTML='<input type="button" value="prev" onClick="cal.getMonth()">'; 
    }); 

가, 버튼을 만들어집니다하지만 때 그것을를 눌러 디버그는 말합니다 : "cal '은 정의되지 않았습니다."

감사합니다.

+1

잘못된 코드를. cal.month 대신 this.month를 작성하십시오. – scripter

+0

jquery를 사용하지만 jquery를 사용하지 말아야합니다. 네이티브 javascript와 jQuery를 혼합하는 것은 좋지 않습니다. 하나의 방법을 선택하고 함께 가십시오. –

+0

다음은 순수한 jQuery 구현 예제입니다. http://jsfiddle.net/YgtC4/1/ –

답변

4

당신은이 :

Calendar.prototype.getMonth = function() { 
    alert(cal.month); 
} 

변수가 여기에 정의되어 있지 않습니다. 사용하는 대신이 :

Calendar.prototype.getMonth = function() { 
    alert(this.month); 
} 
0
Function Calender(){ 
this.month = "jan"; 
} 
Calender.prototype.getMonth = function(){ 
alert(this.month); 
} 
+0

답변에 몇 가지 설명을 추가하십시오. 그런 식으로, OP는 이해하지 않고 변경 사항을 복사/붙여 넣기하는 대신 질문에서 배울 수 있습니다. – Walls