JSDoc document final method

Viewed 83

Is there a way to document a final method in JS using JSDoc.

A final method in Java is one which can't be overridden.

I couldn't find any option in JSDoc website.

1 Answers

It would seem you can't, since a search of the JSDoc documentaton for final turns up no results.

This isn't all that surprising, because you can't reliably have a final method in JavaScript. So if it's important for a method not to be overridden, you'll probably have to resort to documenting that in its description. Still, it would be possible for JSDoc to provide a way to annotate that for tools to pick up on, it just doesn't seem to have it.

Here's an unreliable way to have a final method in JavaScript:

class Base {
    constructor() {
        if (this.finalMethod !== Base.prototype.finalMethod) {
            throw new Error(`You must not override 'finalMethod' in your subclass.`);
        }
    }
    
    finalMethod() {
        console.log("This is the pseudo-final method");
    }
}

class Derived extends Base {
    finalMethod() {
        console.log("This is the overridden method");
    }
}

const d = new Derived(); // Throws error

But that's easily overcome in any of several ways:

  • Wait to create the method until your subclass constructor has already called the superclass constructor.
  • Return an object created without using the superclass constructor (for instance, return Object.assign(Object.create(this), { finalMethod() { /*...*/ } }); (Although now I think of it, that's really just a different way to do #1 above.)
  • Return a proxy.
  • Create your subclass instances without ever calling the superclass constructor (not recommended — but then, none of these are)
  • ...probably others...
Related