好吧,我刚刚制作了一个计算器,在Chrome上测试时,我遇到了这个错误 “未捕获的ReferenceError:g未定义 (匿名函数)“。即使我刚刚使用
定义它function chart(principal, interest, monthly, payments) {
var graph = document.getElementById("graph");
graph.width = graph.width;
if (arguments.length == 0 || !graph.getContext) return;
var g = graph.getContext("2d");
//g is defined here yet on line 147, i get the
//error
var width = graph.width,
height = graph.height;
function paymentToX(n) {
return n * width / payments;
}
function amountToY(a) {
return height - (a * height / (monthly * payments * 1.05));
}
g.moveTo(paymentToX(0), amountToY(0));
g.lineTo(paymentToX(payments),
amountToY(monthly * payments));
g.lineTo(paymentToX(payments), amountToY(0));
g.closePath();
g.fillStyle = "#f88";
g.fill();
g.font = "bold 12px sans-serif";
g.fillText("Total Interest Payments", 20, 20);
var equity = 0;
g.beginPath();
g.moveTo(paymentToX(0), amountToY(0));
for (var p = 1; p <= payments; p++) {
var thisMonthsInterst = (principal - equity) * interest;
bal -= (monthly - thisMonthsInterst);
g.lineTo(paymentToX(p), amountToY(bal));
}
g.lineWidth = 3;
g.stroke();
g.fillStyle = "black";
g.fillText("Loan Balance", 20, 20);
g.textAlign = "center";
var y = amountToY(0);
var x = paymentToX(year * 12);
g.fillRect(x - 0.5, y - 3, 1, 3);
if (year == 1) g.fillText("Year", x, y - 5);
if (year % 5 == 0 && year * 12 !== payments) g.fillText(String(year), x, y - 5);
}
g.lineWidth = 3;
g.stroke();
g.fillStyle = "black";
g.fillText("Loan Balance", 20, 20);
g.textAlign = "center";
var y = amountToY(0);
var x = paymentToX(year * 12);
g.fillRect(x - 0.5, y - 3, 1, 3);
if (year == 1) g.fillText("Year", x, y - 5);
if (year % 5 == 0 && year * 12 !== payments) g.fillText(String(year), x, y - 5);
g.textAlign = "right";
g.textBaseline = "middle";
}
即使修改它,我仍然有同样的错误。
答案 0 :(得分:2)
g.textAlign和g.textBaseline在你定义g
的函数之外答案 1 :(得分:0)
函数chart
在g.lineWidth = 3
之前结束。除此之外的所有内容都没有g
的定义。