我正在使用一個使用Revealing Module Pattern的小腳本。Javascript揭示模塊模式和咖啡腳本
隨着goold醇'Javascript的一切工作正常,但我想知道如何轉移到Coffeescript。
拿這個作爲一個例子:
// revealing module pattern
var anchorChange4 = function() {
// this will be a private property
var config = {
colors: [ "#F63", "#CC0", "#CFF" ]
}
// this will be a public method
var init = function() {
var self = this; // assign reference to current object to "self"
// get all links on the page
var anchors = document.getElementsByTagName("a");
var size = anchors.length;
for (var i = 0; i < size; i++) {
anchors[i].color = config.colors[i];
anchors[i].onclick = function() {
self.changeColor(this, this.color); // this is bound to the anchor object
return false;
};
}
}
// this will be a public method
var changeColor = function (linkObj, newColor) {
linkObj.style.backgroundColor = newColor;
}
return {
// declare which properties and methods are supposed to be public
init: init,
changeColor: changeColor
}
}();
等於這CoffeeScript中:
anchorChange4 = ->
config = colors: [ "#F63", "#CC0", "#CFF" ]
init = ->
self = this
anchors = document.getElementsByTagName("a")
size = anchors.length
i = 0
while i < size
anchors[i].color = config.colors[i]
anchors[i].onclick = ->
self.changeColor this, @color
false
i++
changeColor = (linkObj, newColor) ->
linkObj.style.backgroundColor = newColor
init: init
changeColor: changeColor
init
和changeColor
暴露在全球範圍內和JavaScript工作正常,但是CoffeeScript的事情會失敗,因爲它沒有方法'init'。
需要做些什麼才能將此揭示模塊模式轉換爲CoffeeScript?
我也對如何讓它變得更好提供建議。 ;-)
感謝, 多米尼克
無需使用'while'環和增量'手動i';使用'for i in [0 ... size]' –