我对下面的代码片段困惑了很长时间:
/**
* 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;
基本上,我需要创建一个新类型,但对何时使用哪个类型感到非常困惑?
最佳答案
which one to use when?
这在某种程度上是个人喜好和编码风格的问题。 Closure Compiler 更倾向于在 Java 中使用类、接口(interface)、方法等发现的伪经典继承模式,这与其他方法不同。参见 Inheritance Patterns in JavaScript迈克尔·博林。
另见 Annotating JavaScript for the Closure Compiler其中对各种标签的定义最简洁。
对于我自己,我使用伪经典继承模式。因此,99% 的时间我都使用 @constructor
定义类,这些类将与 new
关键字一起使用。这些类也用 @struct
标记,因此它们具有一组固定的属性和方法。我的大约 80% 的类声明它们是 @implement
和 @interface
因为这允许我使用接口(interface)类型而不是绑定(bind)到特定的类实现。
有时我会使用@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;
我可以在别处使用那个 typedef:
/** 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。
关于javascript - 什么时候在闭包中使用 typedef?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36770632/