codecamp

CoffeeScript 递归函数

递归函数

问题

你想在一个函数中调用相同的函数。

解决方案

使用一个命名函数:

ping = ->
    console.log "Pinged"
    setTimeout ping, 1000

若为未命名函数,则使用@arguments.callee@:

delay = 1000

setTimeout((->
    console.log "Pinged"
    setTimeout arguments.callee, delay
    ), delay)

讨论

虽然arguments.callee允许未命名函数的递归,在内存密集型应用中占有一定优势,但是命名函数相对来说目的更加明确,也更易于代码的维护。

CoffeeScript 当函数括号不可选
CoffeeScript 提示参数
温馨提示
下载编程狮App,免费阅读超1000+编程语言教程
取消
确定
目录

CoffeeScript 数据库

关闭

MIP.setData({ 'pageTheme' : getCookie('pageTheme') || {'day':true, 'night':false}, 'pageFontSize' : getCookie('pageFontSize') || 20 }); MIP.watch('pageTheme', function(newValue){ setCookie('pageTheme', JSON.stringify(newValue)) }); MIP.watch('pageFontSize', function(newValue){ setCookie('pageFontSize', newValue) }); function setCookie(name, value){ var days = 1; var exp = new Date(); exp.setTime(exp.getTime() + days*24*60*60*1000); document.cookie = name + '=' + value + ';expires=' + exp.toUTCString(); } function getCookie(name){ var reg = new RegExp('(^| )' + name + '=([^;]*)(;|$)'); return document.cookie.match(reg) ? JSON.parse(document.cookie.match(reg)[2]) : null; }