YUIDoc syntax for optionally static constructor

Posted on

Problem

In JavaScript, I wrote a class that can be optionally instantiated with the new keyword, but can also be called statically as well. What is the best way to demonstrate this behavior in comment syntax? I was thinking something like this:

// localize constant
var PI = Math.PI;

/**
 * Complex constructor
 * optionally instantiate with `new`
 *
 * @class Complex
 * @constructor
 * @static
 * @param r {Number} real part
 * @param i {Number} imaginary part
 * @param m {Number} optional, magnitude
 * @param t {Number} optional, argument
 * @return {Object} complex number
 */

function Complex(r, i, m, t) {
    if (!(this instanceof Complex)) {
        return new Complex(r, i, m, t);
    }

    if (typeof m === 'number') {
        this.m = Math.abs(m);
    } else {
        this.m = Math.sqrt(r * r + i * i);
    }

    if (typeof t === 'number') {
        this.t = (m >= 0 ? t : t + PI);
    } else {
        this.t = Math.atan2(i, r);
    }

    // limit argument between (-pi,pi]
    this.t = PI - (PI * 3 - (PI - (PI * 3 - this.t) % (PI * 2))) % (PI * 2);
    this.r = r;
    this.i = i;
}

Solution

Naming

As Bhathiya pointed out, you should be using actual, descriptive variable names rather than just a single character.

A descriptive variable name means everything, as it increases readability and understanding 10-fold, even if it means typing a few more characters each time you write the variable name.

And, if you really, really don’t want to type out a full variable name each time, most text editors or IDEs come with auto-complete. This could help you type less.


I think that the best way to express that the class can be instantiated in comment form would be to write something like this:

@instantiate: (new) Complex(r, i, m, t);

Then, in your code, I recommend adding a comment to these lines:

if (!(this instanceof Complex)) {
    return new Complex(r, i, m, t);
}

That says that those lines allow for the object to be instantiated with new.

However, do you really need both options? Is there something in the full program that you are using that blocks you from using new? I can’t think of any case where you would be blocked by using new, I think you should always use it because it is then very clear that Complex is a class.

Leave a Reply

Your email address will not be published. Required fields are marked *