javascript - JS OOP: methods on prototype vs methods in constructor function -
this question has reply here:
use of 'prototype' vs. 'this' in javascript? 12 answerslet me set first 2 examples.
example 1:
function gallery() { this.a = "i 'a'"; this.trace = function() { console.log(this.a); } }
example 2:
function gallery() { this.a = "i 'a'"; } gallery.prototype.trace = function () { console.log(this.a); }
obviously, both things same. question is: there drawback using method definition in constructor function on prototype one? difference anyway?
is prototype more memory friendly? assume if define method within constructor function, every single gallery instance have 'own instance' of method consume more memory while prototype defines 1 function that's shared across gallery instances. correct?
thanks lot!
the method definition in constructor slower because it's executed every single time create new object.
on other hand, prototype
, vm able optimize access it, optimize functions (since they're shared - wouldn't able if every instance had own functions).
(not going much details because it's been explained already, basically, vms (i know v8 that, not sure others do) "hidden class" every prototype, optimized fields, instead of having map of => any)
this allows lot more of flexibility add together functions @ later time.
the thing adding methods on object can false "private" fields more easily.
javascript oop constructor prototype
No comments:
Post a Comment