答案 0 :(得分:4)
你可以在最后摆脱半冒号,也摆脱了大量的括号和花括号。
Green5 =
getLevel: -> @options.level
setLevel: (x) ->
greenlevels = @options.greenlevels;
level = Math.floor Math.min greenlevels.length-1, Math.max 0,x
@options.level = level
@element.css background: greenlevels[level]
@_trigger 'change', 0, level
_init: -> @setLevel this.getLevel() # grab the default value and use it
darker: -> @setLevel this.getLevel() - 1
lighter: -> @setLevel this.getLevel() + 1
off: ->
@element.css background: 'none'
@_trigger 'done'
@destroy() # use the predefined function
options: level: 15, greenlevels: ['#000','#010','#020','#030','#040','#050','#060','#070','#080','#090','#0a0','#0b0','#0c0','#0d0','#0e0','#0f0', '#fff']
$.widget "ui.green5", Green5
但是,语法糖并不是CoffeeScript的唯一好处。一个很大的优点是它将某些代码结构重写为更好的javascript。
例如:
yearsOld = max: 10, ida: 9, tim: 11
ages = for child, age of yearsOld
child + " is " + age
变为:
var age, ages, child, yearsOld;
yearsOld = {
max: 10,
ida: 9,
tim: 11
};
ages = (function() {
var _results;
_results = [];
for (child in yearsOld) {
age = yearsOld[child];
_results.push(child + " is " + age);
}
return _results;
})();
变量全部被正确声明,并且在ages for loop
周围自动添加了一个闭包,这个闭包是用良好的javascript技术编写的,这显然是非常难以阅读。