2016-11-11 71 views
1

我最近围绕JS代码戳返回类型,我发现了以下注释:明确设置的功能

/** 
* Explicitly set the return type here to prevent the primitive being lost when using new 
* @return {boolean} 
*/ 
function giveMeABoolean(please) { 
    ... 
} 

是怎么回事?在JS中返回类型?我一直在网上搜索,无法找到任何关于此的信息。经过一些测试后,使用没有注释时,原语确实丢失。任何人都可以解释这个注释如何工作?

+0

注释不改变行为的。所有评论都被口译员抛弃。 –

回答

4

那些评论是JSDoc,这只是一种方式,你可以记录你的代码。像IDE这样的工具可以获取这些文档,并在尝试了解某种方法的API时以很好的格式显示给您。

当他们进行静态分析以帮助为智能感知等提示提示时,某些工具也可能包含此信息。这会给开发人员一个印象,即在处理代码时,返回值的“类型”会保留/已知。但是,这些评论在运行时不会有任何影响。

Here's the documentation for the @return comment.这里是一个的提供有相关例子:

/** 
* Returns the sum of a and b 
* @param {Number} a 
* @param {Number} b 
* @param {Boolean} retArr If set to true, the function will return an array 
* @returns {Number|Array} Sum of a and b or an array that contains a, b and the sum of a and b. 
*/ 
function sum(a, b, retArr) { 
    if (retArr) { 
     return [a, b, a + b]; 
    } 
    return a + b; 
} 
2

我认为该代码的作者正在提供该信息用于文档目的。如果你真的想提供类型信息,你可能会考虑typescriptflow