Martin
Martin

Reputation: 24308

Adding multiple methods to a JavaScript prototype?

I am trying to find if its possible and disadvantages adding an object to a prototype, for example

myObject.prototype = {

    init: function () {

    },

    runMe: function () {

    },

    removeItems: function () {

    }
}

Is this actually legal, and what's the difference for doing each one separately i.e.

myObject.prototype.init = function () {}

myObject.prototype.runMe = function () {}

I tried looking for MDN documentation about adding as an object but couldn't find anything. Can anyone comment on recommended ways of doing this?

Upvotes: 3

Views: 3860

Answers (3)

Audun Olsen
Audun Olsen

Reputation: 628

I would do it like this with the help of some ES6 flavour:

myObject.prototype = { ...myObject.prototype,

    init: function () {

    },

    runMe: function () {

    },

    removeItems: function () {

    }
}

Succinct and you don't have to worry about overwriting anything like you do with @JLRishe's accepted answer.

Upvotes: 2

rockariotphobia
rockariotphobia

Reputation: 186

Another way to add multiple functions to the object prototype is like this:

(function() {
    this.init = function () {

    };

    this.runMe = function () {

    };

    this.removeItems = function () {

    };
}).call(myObject.prototype);

Take a look at this documentation on Closures from MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures#Performance_considerations

Upvotes: 3

JLRishe
JLRishe

Reputation: 101662

Either approach is fine, and you should choose whichever approach makes it easier to do whatever you're doing. If this is the only place that you modify the prototype, then the only meaningful difference is that the first approach wipes away the constructor property that's on the prototype by default.

For that reason, if you do overwrite the whole prototype, you should make sure to re-add its constructor:

myObject.prototype = {

    init: function () {

    },

    runMe: function () {

    },

    removeItems: function () {

    },
    // right here
    constructor: myObject
}

Upvotes: 7

Related Questions