简体   繁体   English

原型方法中的“ x未定义”

[英]“x is undefined” in prototype method

I'm stuck with the following code: 我坚持下面的代码:

I have the following code: 我有以下代码:

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()">';
    });

when running this, the button is created but when pressing it the debug says: "'cal' is undefined" 运行此按钮时,将创建该按钮,但是按下该按钮时,调试会显示:“'cal'未定义”

Thanks for the help. 谢谢您的帮助。

You have: 你有:

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

The cal variable is not defined here. 此处未定义cal变量。 Use this instead: 使用代替:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM