gpt4 book ai didi

javascript - 显式设置函数的返回类型

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:21:49 24 4
gpt4 key购买 nike

我最近在研究 JS 代码,发现了以下注释:

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

什么给了? JS 中的返回类型?我一直在网上四处闲逛,找不到任何相关信息。经过一些测试,在没有注释的情况下使用 new 时,原语确实丢失了。谁能解释一下这个注释是如何工作的?

最佳答案

这些评论是 JSDoc ,这只是您记录代码的一种方式。当您试图理解某个方法的 API 时,诸如 IDE 之类的工具可以利用此文档并以漂亮的格式向您展示它。

有些工具在进行静态分析时也可能包含此信息,以帮助您提示智能感知等功能。这会给开发人员一种印象,即在他们使用代码时,返回值的“类型”是保留/已知的。但是,这些注释不会在运行时产生任何影响。

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;
}

关于javascript - 显式设置函数的返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40553135/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com