javascript - performance benefits of using js prototype for structuring large js application -


what benefit of this:

hb.somepackage = hb.somepackage || {};  hb.somepackage.somegoodclass = function(someselector){     this.someselector = someselector; }  hb.somepackage.somegoodclass.prototype.dosomestuff = function(){     var $obj = $(this.someselector);     // work magic $obj; }; 

as opposed this:

hb.somepackage = hb.somepackage || {};  hb.somepackage.someselector = "hardcodedvaluehere";  hb.somepackage.someotherselector = "anotherhardcodedvaluehere";  hb.somepackage.somereallybadclass = function(){};  hb.somepackage.somereallybadclass.prototype.dosomestuff = function(){}; 

there's sort of lot consider in question. cover basics, comes down prototypal inheritance , lookup.

your first example:

hb.somepackage = hb.somepackage || {};  hb.somepackage.somegoodclass = function(someselector){     this.someselector = someselector; }  hb.somepackage.somegoodclass.prototype.dosomestuff = function(){     var $obj = $(this.someselector);     // work magic $obj; }; 

this makes someselector property of somegoodclass can change depending on callee. if create/call function binded different context, this.someselector correspond callee context:

var newobject = {someselector : 'oldselector'}; hb.somepackage.somegoodclass.apply(newobject, 'newselector'); newobject.someselector; // 'newselector' hb.somepackage.somegoodclass.someselector; // undefined 

codepen: http://codepen.io/anon/pen/yeenxj

so here, may have thought inside of somegoodclass this.someselector have referred somegoodclass.someselector doesn't.

in second example:

hb.somepackage = hb.somepackage || {};  hb.somepackage.someselector = "hardcodedvaluehere";  hb.somepackage.someotherselector = "anotherhardcodedvaluehere";  hb.somepackage.somereallybadclass = function(){};  hb.somepackage.somereallybadclass.prototype.dosomestuff = function(){}; 

someselector more or less being used type of constant need referenced inside of other functions of somepackage

depending on context of application , desired/preferred coding practices 1 may desired on other. in second example, calling apply() or call() on somegoodclass function not change "internal" someselector attribute of class wouldn't able lookup attribute within function/object.


Comments