关于记录JavaScript的问题:JS类型

Bra*_*roy 5 javascript conventions naming-conventions

考虑到我将来会与一个更大的团队合作,我正在尝试自学一些前端语言的基本注释和文档原则.目前我正在研究JS.

在大多数情况下,我使用Google的风格指南作为首选,但我仍然有一些问题.

假设我有一个像这样的ajax函数:

function initFunction(src, wrapper) {
  $.getJSON(src, {
    format: "json"
  }).done(function(data) {
    var wrapper = $(wrapper),
      contents = callAnotherFunction($(data)[0]);

    // Populates the wrapper element.
    wrapper.append(contents );

  }).fail(function(jqXHR, textStatus, errorThrown) {
    alert(textStatus + ": " + errorThrown);
  });
}
Run Code Online (Sandbox Code Playgroud)

该函数有两个@param,src和包装器.这是一些问题.

然后,callAnotherFunction()将Object作为参数,它应该返回一些HTML.

  1. 什么是src的类型?考虑到它的JSON, {Object}
  2. 什么是包装类型?考虑到它是一个像"#myId"String 这样的值?
  3. 这个函数的返回类型是什么?这是一个无效函数,但我不知道我称之为返回类型.它会返回null吗?
  4. 你可以附加到元素的HTML类型是什么?是一个String吗?
  5. 显示所有这些的JSDoc约定是什么?像这样的东西?

/** * This is a description of this function. It gets a JSON file, uses it as * a jQuery object, and then call another function with the new data. * @param {Object} src JSON file to parse. * @param {String} wrapper HTML element to use as a wrapper for the output. * @return {Null} */

Ema*_*ola 7

  1. 参数的类型与它所代表的内容无关,而是参数的JavaScript类型.在你的情况下src是一个包含url的字符串(检索url并不重要,检索JSON),因此类型是字符串.更多信息在这里.
  2. 是的,这是一个字符串.
  3. 如果函数没有返回值,请不要在JSDoc中提及它.
  4. 根据JQuery文档,它是:

键入:htmlString或Element或Array或jQuery

DOM元素,元素数组,HTML字符串或要在匹配元素集中的每个元素末尾插入的jQuery对象.

因此,这取决于您想要将您的功能记录为接受的内容.如果要将其记录为接受多种类型,则使用括号和|字符(下面的示例).

  1. 关闭,但您不需要返回类型.有些人还在描述和参数之间加了一个空行,但解析器并不需要这样做.

    /**
     * This is a description of this function. It gets a JSON file, uses it as 
     * a jQuery object, and then call another function with the new data.
     *
     * @param  {Object} src     JSON file to parse.
     * @param  {(String|jQuery|DOMElement)} wrapper HTML element to use as a wrapper for the output.
     */
    function initFunction(src, wrapper) {
    // ...
    
    Run Code Online (Sandbox Code Playgroud)

    在上面,我们已经指出wrapper可以是字符串,jQuery对象或DOMElement.我们没有深入了解它可能是一个数组,也不知道字符串是选择器还是HTML片段.描述需要处理.有很多选择,你可能不得不依赖{*}.

    如果解析器可能无法判断这是否是一个函数,您还可以添加@function标记:

    /**
     * This is a description of this function. It gets a JSON file, uses it as 
     * a jQuery object, and then call another function with the new data.
     *
     * @function
     *
     * @param  {Object} src     JSON file to parse.
     * @param  {(String|jQuery|DOMElement)} wrapper HTML element to use as a wrapper for the output.
     */
    var initFunction = function(src, wrapper) {
    // ...
    
    Run Code Online (Sandbox Code Playgroud)

    根据上下文,你可能更喜欢@method@function(他们是同义词).