何时在闭包中使用 typedef
When to use typedef in closure?
我对以下代码片段感到困惑了很长时间:
/**
* 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。
相关文章:
- 在underscorejs模板中使用闭包
- setTimeout可以与闭包内的函数一起使用吗
- 附加到原型属性的Do函数没有闭包
- 使用闭包共享构造函数参数
- 使用Google闭包编译器包含一个Ecmascript 6类
- 从js引擎的角度来看闭包和构造函数是如何工作的
- for循环中的JavaScript闭包
- Javascript闭包-如何防止内存泄漏
- 子类访问父类's闭包变量
- 闭包如何具体化数据封装
- Javascript.闭包和dynamic'这'实际上具有约束力
- 构造函数函数闭包变量
- 闭包js框架-将ArrayBuffer转换为字符串
- 如何在Angularjs中重构闭包中的重复代码
- 如何告诉闭包javascript编译器不要混淆webkitAudioContext的方法名称
- Google闭包和生成的getters/ssetter
- 如何冻结函数's在闭包中的变量
- 如何使用外部Javascript库(如jQuery)重命名Google闭包样式表
- 使变量可用于不带闭包的异步调用
- 何时在闭包中使用 typedef