gpt4 book ai didi

javascript - 原型(prototype)方法中的"x is undefined"

转载 作者:行者123 更新时间:2023-11-28 15:42:48 25 4
gpt4 key购买 nike

我被以下代码困住了:

我有以下代码:

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’未定义”

感谢您的帮助。

最佳答案

你有:

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

此处未定义 cal 变量。使用这个代替:

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

关于javascript - 原型(prototype)方法中的"x is undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23300762/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com