javascript - Using a prototype pattern in a closure -
i've been fiddling around bit prototype , closure patterns in javascript. might know, there's performance penalty when using closure pattern because redefines same functions every instance of object. however, closure pattern allow private variables, makes encapsulation easier.
here's typical example of prototype pattern:
function foo(val) { this.val = val; } foo.prototype.getval = function() { return this.val; } var f = new foo(42);
i thinking, why can't this?
function parent() { } parent.prototype.getval = function() { return this.val; } function foo(val) { function obj { this.val = val; } obj.prototype = new parent(); return new obj(); } var f = foo(42); // note missing 'new'
this allows private variables in foo() function, , can dynamically set prototype in foo() function.
i made jsperf.com test indeeds shows big difference in performance, don't know why.
the difference in performance beacuse creating 2 objects instead of one. creating 1 object use prototype other.
if want create lot of objects this, should create 1 prototype object , use prototype objects create.
Comments
Post a Comment