Search code examples
javascriptintellij-ideawebstormjsdoc

How can I document a 'this' instance inside a callback function in WebStorm?


Having this code:

function Element() {
    this.name = "yay";
}
Element.prototype.extend = function(object) {
    if (object instanceof Object) {
        for (var n in object) {
            if (object.hasOwnProperty(n)) {
                this[n] = object[n];
            }
        }
    }
};

var el = new Element();
el.extend({
    update: function() {
        console.log(this.name);
    }
});

I want WebStorm to know that update() this is an instance of Element, but I don't really know how to do it.

The maximum I've reached is this:

el.extend({
    /**
      * @this Element
      */
    update: function() {
        console.log(this.name);
    }
});

But I don't want to do that in every extend().

Also found this:

/**
 * @typedef {Object} FunctionExtend
 */
/**
 * @param {FunctionExtend} object
 */
Element.prototype.extend = function(object) {
    [...]

But I'm stuck in:

  • How to declare FunctionExtend to have undefined number of parameters.
  • How to tell that each @parameter will be a callback without knowing the parameter name.
  • How to tell what is the @this of the callbacks.

Solution

  • Extending prototypes to begin with is generally a Bad Idea™, and it does not play well with write-time documentation tools like JSDoc.

    You will probably have no choice but to document every function individually.