我有一个问题。 以下脚本通过 JSLint 时不会出现错误。 请不要投票反对我。该脚本仅用于学习目的,以便更好地理解闭包。如果您更了解,请发布您的解决方案。
问题是当我使用 JSLint 检查代码时收到以下错误消息:
JSLint was unable to finish. 43.8Expected ';' and instead saw '}'
这是我的脚本
var c = document.querySelector("#c");
var ctx = c.getContext("2d");
var path = function () {
return {
innerTri: function (x, y, width, height, fill, stroke) {
x = x || 0;
y = y || 0;
fill = fill || "yellow";
stroke = stroke !== undefined ? stroke : fill;
if (width === undefined || height === undefined) {
alert("You need to provide width and height");
return false;
}
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x = x + width, y);
ctx.lineTo(x, y = y + height);
ctx.closePath();
ctx.fillStyle = fill;
ctx.strokeStyle = stroke;
ctx.fill();
ctx.stroke();
},
outRect: function (x, y, width, height, stroke) {
x = x || 0;
y = y || 0;
stroke = stroke || "black";
if (width === undefined || height === undefined) {
alert("You need to provide width and height");
return false;
}
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(x = x + width, y);
ctx.lineTo(x, y = y + height);
ctx.lineTo(x = x - width, y);
ctx.strokeStyle = stroke;
ctx.closePath();
ctx.stroke();
}
}
} //this is the position 43.8
var a = path();
a.innerTri(225, 225, 50, 50, "yellow", "green");
a.outRect(200, 200, 100, 100, "blue");
如果我在那里放一个分号,那么每一行都会收到错误消息。 该脚本按我的预期工作,但我无法对此错误执行任何操作。
谢谢
最佳答案
好的,所以您正在使用极其严格的 linting 规则。
以下是我需要更改才能使 linter 满意的事项列表:
- 在 return 语句和路径函数声明之后添加分号
- 将
"use strict";
语句放在path
函数顶部 - 删除
lineTo()
参数列表内的内联变量赋值 - 声明您正在使用
window
作为全局对象(在 JSLint 设置中) - 调用
window.alert()
而不仅仅是alert()
- 声明 JSLint 假设此代码将在浏览器中使用(在 JSLint 设置中)
- 确保每一级缩进与上一级缩进正好有 4 个空格
生成的代码如下所示:
var c = document.querySelector("#c");
var ctx = c.getContext("2d");
var path = function () {
"use strict";
return {
innerTri: function (x, y, width, height, fill, stroke) {
x = x || 0;
y = y || 0;
fill = fill || "yellow";
if (stroke === undefined) {
stroke = fill;
}
if (width === undefined || height === undefined) {
window.alert("You need to provide width and height");
return false;
}
ctx.beginPath();
ctx.moveTo(x, y);
x = x + width;
ctx.lineTo(x, y);
y = y + height;
ctx.lineTo(x, y);
ctx.closePath();
ctx.fillStyle = fill;
ctx.strokeStyle = stroke;
ctx.fill();
ctx.stroke();
},
outRect: function (x, y, width, height, stroke) {
x = x || 0;
y = y || 0;
stroke = stroke || "black";
if (width === undefined || height === undefined) {
window.alert("You need to provide width and height");
return false;
}
ctx.beginPath();
ctx.moveTo(x, y);
x = x + width;
ctx.lineTo(x, y);
y = y + height;
ctx.lineTo(x, y);
x = x - width;
ctx.lineTo(x, y);
ctx.strokeStyle = stroke;
ctx.closePath();
ctx.stroke();
}
};
};
var a = path();
a.innerTri(225, 225, 50, 50, "yellow", "green");
a.outRect(200, 200, 100, 100, "blue");
关于javascript - 我的脚本在 JSLint 中失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44606932/