回调函数的注释

7

我很好奇,如何很好地注释回调函数将传递哪些参数。

假设我们有以下代码和不完整的注释:

/**
 * an utterly useless function
 *
 * @param {String} an useless string
 * @param {Boolean} an useless boolean
 * @param {Function} ???
 */

function Useless (str, bool, callback) {
  callback(str, bool);
}

回调函数将使用字符串和布尔值作为参数被调用,是一个不错的表述方式。

回调函数传递了 strbool 类型?我不确定问题出在哪里。 - Dave Newton
问题在于如何以清晰的方式对其进行注释。 - Max
说回调函数将传递另外两个参数有什么问题? - Dave Newton
请看Charlie Rudenstål的回复。这是我所采用的方式,也是我不满意的原因。我觉得它很冗长,并希望有人能提供一个"{Type}描述"风格的模式,让我可以使用。 - Max
1
第一个例子过于冗长,我怀疑是故意这样做的。我只会说 callback(str, bool) 并添加必要的上下文信息。其他任何内容都应该放在主要文档中,而不是参数文档中。 - Dave Newton
显示剩余2条评论
4个回答

5
通常你只需要编写一个带有易于理解的名称的函数调用:
/* 
 * @param {String} input: the text
 * @param {Function} callback(output, hasChanged): called after calculation
 */

或者,如果需要解释参数,您可以使用多行描述:
/* 
 * @param {String} input: the text
 * @param {Function} callback(result, change)
 *         the function that is called after calculation
 *         result {String}: the output of the computation
 *         change {Boolean}: whether a change has occurred
 */

2

我不知道这方面是否有任何约定俗成的规则。我会建议你直接使用以下内容:

@param {Function} Called on success with the response (string) as the first param and the status code (int) as the second

我知道这段话有些啰嗦。

另一个选项是采用这种方式进行操作(类似于jQuery的做法,在我所知道的代码中不是这样的,但在他们的文档中是这样做的)

@param {Function} onSuccess(response, statusCode)

这里有一个例子: http://api.jquery.com/jQuery.ajax/。当然,这是一个选项对象,文档结构与内联文档不同。但是看一下回调函数,你会发现它们很相似。
为了清晰起见,最好使用callback(response, statusCode)而不是callback(string, int)。如果必须选择一个的话,意思在前,类型在后。

是的,那正是我目前的做法,也是我为什么感到不满意的原因。 - Max
更新了一个示例,它的灵感来自于jQuery文档。 - Charlie Rudenstål

0

嗯,有很多种方法可以在JavaScript中添加注释;以下是我的建议/最佳实践

使用///* */更好,因为你可以使用后者来删除包含其他注释的整个块。但是,如果您想使用自动文档生成工具,则必须使用类似于javaDoc样式的注释。

这是一个可以与YUI DOC(最佳)一起使用的示例http://developer.yahoo.com/yui/yuidoc/#start

/**
* This is a description
* @namespace My.Namespace
* @method myMethodName
* @param {String} str - some string
* @param {Object} obj - some object
* @param {requestCallback} callback - The callback that handles the response.
* @return {bool} some bool
*/
    function SampleFunction (str, obj, callback) {
         var isTrue = callback(str, obj); // do some process and returns true/false.
         return isTrue ;
    }

其他参数示例:- http://usejsdoc.org/tags-param.html 希望这能对你有所帮助 :)

0
/**
 * an utterly useless function
 *
 * @param {String} an useless string
 * @param {Boolean} an useless boolean
 * @param {(param1:Number, param2:String ...)=>{}} callback
 */

function Useless (str, bool, callback) {
  callback(str, bool);
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接