【问题标题】:Coffeescript resetCards is not a functionCoffeescript resetCards 不是函数
【发布时间】:2016-04-20 08:20:04
【问题描述】:

我一直在 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

【问题讨论】:

    标签: node.js express compiler-errors coffeescript


    【解决方案1】:

    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 = ->
        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() { } 等价物。

    【讨论】:

    • 谢谢,这行得通,我已经习惯了在 jquery 中使用 $() 函数下面的函数,我是 node、express 和 coffeescript 的新手,所以我想我必须得到曾经有带变量的函数。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-12
    • 2012-11-01
    • 2014-09-12
    • 1970-01-01
    • 2012-02-17
    • 1970-01-01
    相关资源
    最近更新 更多