【发布时间】:2011-11-19 23:58:22
【问题描述】:
可能重复:
What does this mean? (function (x,y)){…}){a,b); in JavaScript
我有以下来自Canvas documentation的JS代码:
for(var i=0;i<4;i++){
for(var j=0;j<3;j++){
ctx.beginPath();
var x = 25+j*50; // x coordinate
var y = 25+i*50; // y coordinate
var radius = 20; // Arc radius
var startAngle = 0; // Starting point on circle
var endAngle = Math.PI+(Math.PI*j)/2; // End point on circle
var anticlockwise = i%2==0 ? false : true; // clockwise or anticlockwise
ctx.arc(x,y,radius,startAngle,endAngle, anticlockwise);
if (i>1){
ctx.fill();
} else {
ctx.stroke();
}
}
}
我想把它变成一个 CoffeeScript 代码。这里是:
@draw = ->
canvas = document.getElementById('canvas')
ctx = canvas.getContext('2d')
for i in [0..3]
for j in [0..2]
ctx.beginPath()
x = 25 + j * 50
y = 25 + i * 50
radius = 20
startAngle = 0
endAngle = Math.PI + (Math.PI * j) / 2
anticlockwise = if i % 2 == 0 then false else true
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise)
if i > 1 then ctx.fill() else ctx.stroke()
一切都很好,但我有一个关于编译代码的问题:
this.draw = function() {
var anticlockwise, canvas, ctx, endAngle, i, j, radius, startAngle, x, y, _results;
canvas = document.getElementById('canvas');
ctx = canvas.getContext('2d');
_results = [];
for (i = 0; i <= 3; i++) {
_results.push((function() {
var _results2;
_results2 = [];
for (j = 0; j <= 2; j++) {
ctx.beginPath();
x = 25 + j * 50;
y = 25 + i * 50;
radius = 20;
startAngle = 0;
endAngle = Math.PI + (Math.PI * j) / 2;
anticlockwise = i % 2 === 0 ? false : true;
ctx.arc(x, y, radius, startAngle, endAngle, anticlockwise);
if (i > 1) {
_results2.push(ctx.fill());
} else {
_results2.push(ctx.stroke());
}
}
return _results2;
})());
}
return _results;
};
那么,为什么'()' 括号出现在return _results2; 行之后?没什么大不了的:代码做得很好,但是有点完美主义,我想知道如何消除这些圆括号。
UPD:谢谢。现在我明白了,什么是'()'。但是,我仍然有一个问题:为什么会出现?
【问题讨论】: