When to use typedef in closure?

I have been confused for a long time regarding the following piece of code:

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

against

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

Basically, I need to create a new type and get very confused which one to use when?

+4
source share
1 answer

which can be used when?

This is to some extent a matter of personal preference and coding style. The Closure Compiler is more inclined to the pseudo-classical inheritance pattern found in Java, with classes, interfaces, methods, etc., which are different from other approaches. See Inheritance Patterns in Michael Bolin JavaScript .

. JavaScript Closure, .

. 99% @constructor, new. @struct, . 80% , @implement a @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;

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, .

+2

All Articles