咖啡标记重置卡不是一个function

我已经在nodejs上运行了coffeescript和expressjs,我正在制作一个脚本给你9个随机的纸牌(没有重复的),我做了一个函数resetCards在每次显示之后重置卡片,但是当我运行脚本时给我:

TypeError: resetCards is not a function at Object.<anonymous> (/home/zunon/projects/xKoot/router.js:10:1) at Module._compile (module.js:398:26) at Object.Module._extensions..js (module.js:405:10) at Module.load (module.js:344:32) at Function.Module._load (module.js:301:12) at Module.require (module.js:354:17) at require (internal/module.js:12:17) at Object.<anonymous> (/home/zunon/projects/xKoot/xkoot.js:6:10) at Module._compile (module.js:398:26) at Object.Module._extensions..js (module.js:405:10) 

这是文件router.coffee:

 express = require 'express' router = express.Router() cards = [] resetCards() router.route '/randomcard' .get (req, res) -> cardNames = [] for i in [1..9] by 1 cardNames[i] = createCardName() console.log cardNames res.render 'randomcard', {cardNames} return createCardName = -> position = Math.floor Math.random() * cards.length cards.splice position, 1 cards[position] resetCards = -> for i in [1..13] by 1 cards[i - 1] = "club#{i}" cards[i + 12] = "dmnd#{i}" cards[i + 25] = "hart#{i}" cards[i + 38] = "spad#{i}" if i < 3 cards[i + 51] = "joke#{i}" module.exports = router 

CoffeeScript不会像JavaScript那样将函数提升到范围的顶部。 在JavaScript中,如果你说:

 f(); function f() { } 

它将起作用,因为f的定义被提升到顶部,所以代码相当于:

 function f() { } f(); 

但是,CoffeeScript只是将声明提升到最高层,而不是定义 。 所以当在CoffeeScript中这样说的时候:

 f() f = -> 

它在JavaScript中看起来像这样:

 var f; f(); f = function() { }; 

所以当它被调用时, fundefined ,并且你得到一个TypeError

解决方法是将您的resetCards()调用置于resetCards()的定义resetCards

 resetCards = -> for i in [1..13] by 1 cards[i - 1] = "club#{i}" cards[i + 12] = "dmnd#{i}" cards[i + 25] = "hart#{i}" cards[i + 38] = "spad#{i}" if i < 3 cards[i + 51] = "joke#{i}" resetCards() 

另一种看待它的方式是认识到这个CoffeeScript:

 f = -> 

和这个JavaScript一样:

 var f; f = function() { }; 

但是这不完全相同:

 function f() { } 

在CoffeeScript中没有等价的function f() { }

Interesting Posts