何时在闭包中使用 typedef

When to use typedef in closure?

本文关键字:typedef 闭包 何时      更新时间:2023-09-26

我对以下代码片段感到困惑了很长时间:

/**
 * Pair of width and height.
 * @param {string} width
 * @param {string} height
 * @constructor
 * @struct
 */
var Pair = function(width, height) {
  /** @type {string} */
  this.key = key;
  /** @type {string} */
  this.value = value;
};

/**
 * @typedef {{width: string, height: string}}
 */
var Pair;

基本上我需要创建一个新类型,并且对何时使用哪个类型感到非常困惑?

什么时候使用哪一个?

这在某种程度上是个人喜好和编码风格的问题。 闭包编译器更倾向于Java中的伪经典继承模式,包括类,接口,方法等,这与其他方法不同。参见 Michael Bolin的 JavaScript 中的继承模式。

另请参阅闭包编译器的注释 JavaScript,它对各种标签的定义最简洁。

对于我自己,我使用伪经典继承模式。 因此,99% 的时间我都在定义带有@constructor的类,这些类旨在与 new 关键字一起使用。 这些类也标有@struct,因此它们具有一组固定的属性和方法。 大约 80% 的类声明它们@implement @interface,因为这允许我使用接口类型,而不是绑定到特定的类实现。

有时,我会使用 @typedef 来定义具有一些最小属性集的对象。 对我来说,这种类型的对象通常没有定义任何函数,它只是一种聚合某些属性的方法。

下面是我的代码中的一个示例:

/**  A regular expression and the replacement string expression to be used in a
* `String.replace()` command.
* @typedef {{regex: !RegExp, replace: string}}
* @private
*/
Terminal.regexPair;

我可以在其他地方使用该类型定义:

/** Set of regular expressions to apply to each command.
* @type {!Array.<!Terminal.regexPair>}
* @private
*/
this.regexs_ = [];

优点是很容易制作这种类型的东西:

/** Add regular expression and replacement string to be used by `String.replace()`
* for transforming script commands before they are executed.
* @param {!RegExp} regex regular expression for finding a name to transform
* @param {string} replace the replacement string for use with `String.replace()`
*/
Terminal.prototype.addRegex = function(regex, replace) {
  this.regexs_.push({regex:regex, replace:replace});
};

请注意,我使用 {regex:regex, replace:replace} 创建了一个匿名对象,而不是使用 new 运算符。 然而,编译器正在检查此对象是否具有由 Terminal.regexPair 定义的必需(最小)属性集。

但是关于如何编写JavaScript代码还有许多其他哲学。 您当然可以定义一个需要具有指定签名的函数的 typedef。