Search code examples
javascriptprototype

Stylistic convention when adding functions to JS prototypes


As far as I can tell, there is no functional difference in JavaScript between adding multiple functions to an object's prototype like this:

MyObject.prototype.myFunction = function() {
    return this.foo + this.bar;
}
MyObject.prototype.otherFunction = function() {
    return this.foo * this.bar;
}

or this:

MyObject.prototype = {
    myFunction: function() {
        return this.foo + this.bar;
    },
    otherFunction: function() {
        return this.foo * this.bar;
    }
}

Is there any reason to use one over the other? To me, the second option is cleaner because all function declarations sit "inside" of the prototype in terms of indentation. This seems to mostly be a question of style; is there a convention that is followed?


Solution

  • Using

     MyObject.prototype = { }
    

    will override previously defined methods, properties and inheritance. So you might use

    Object.assign(MyObject.prototype, {
       /*...*/
    });
    

    then. I prefer keeping all the prototype methods together so i would go with this variant instead of just assigning every method on its own.