Tuesday 15 April 2014

Should I declare javascript object methods in an object prototype? -



Should I declare javascript object methods in an object prototype? -

this question has reply here:

declaring javascript object method in constructor function vs. in prototype [duplicate] 3 answers

everything have read seems favor declaring methods of object constructor functions in prototype declarations instead of putting method straight initial constructor.

function myclass(name){ this.name = name; } myclass.prototype.callmethod = function(){ console.log(this.name); };

would recommended? if disadvantages putting method within initial constructor so.

function myclass(name){ this.name = name; this.callmethod = function(){ console.log(this.name); }; }

i'm assuming case simple doesn't matter either way, in cases of larger objects implications in declaring method in both stated cases?

from effective javascript, item 34: store methods on prototypes:

storing methods on prototype makes them available instances without requiring multiple copies of functions implement them or properties on each instance object.

storing methods on instance objects creates multiple copies of functions, 1 per instance object. prefer storing methods on prototypes on storing them on instance objects.

javascript methods constructor prototypal-inheritance

No comments:

Post a Comment