Adding sub-properties to an existing property-list

2019-05-09 11:14发布

I am trying to automate a particular module in our JS library and am stuck at a point where I want to define a set of properties (lets say an object that goes as construction parameter of a class).

/**
 * This function initiates world peace!
 * @constructor
 * @param {object}  defaults        - The options to initiate peace.
 * @param {number}  defaults.issues - The number of issues being taken up.
 * @param {string}  defaults.source - The name of the location where process starts.
 */
 var WorldPeace = function (defaults) {
     // code here
 };

It is well and good had all properties of the construction was defined at one location. Unfortunately, my code has a number of modules contributing to that construction properties. Lets say, at some other portion of the code (in a later file) causes to have a couple of more properties

 * @param {Date} defaults.start  - The date when the process started.
 * @param {Date} defaults.stop   - The date when the process should stop.

How do I go about adding to the original set of properties that I had previously defined for WorldPeace function? Doing something like a mixin or subclassing the properties would be going overboard! As such, if I can simply inject to a property list definition it would be great.

2条回答
戒情不戒烟
2楼-- · 2019-05-09 11:40

The easiest method is to use a record type:

/**
 * This function initiates world peace!
 * @constructor
 * @param {{issues: number, source: string}} defaults - options to initiate peace.
 */
var WorldPeace = function (defaults) {
  // code here
};

You could also implement an interface:

/** @interface */
var WordPeaceDefaults;

/** @type {number} */
WorldPeaceDefaults.prototype.issues;

/** @type {string} */
WorldPeaceDefaults.prototype.source;

/**
 * This function initiates world peace!
 * @constructor
 * @param {WorldPeaceDefaults} defaults - options to initiate peace.
 */
var WorldPeace = function (defaults) {
  // code here
};

/**
 * @constructor
 * @implements {WorldPeaceDefaults}
 */
function MyWorldPeaceDefaults() {}

/** @type {number} */
MyWorldPeaceDefaults.prototype.issues = 0;

/** @type {string} */
MyWorldPeaceDefaults.prototype.source = '';

WordPeace(new MyWorldPeaceDefaults);
查看更多
别忘想泡老子
3楼-- · 2019-05-09 11:44

Another way to do it would be to use a typedef:

/** 
 * @typedef {{
 *   issues: number,
 *   source: string
 * }}
 */
var WorldPeaceOptions;

/**
 * @constructor
 * @param {WorldPeaceOptions} defaults
 */
var WorldPeace = function (defaults) {
  // code here
};
查看更多
登录 后发表回答