Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript object construction: whats the difference?

Tags:

javascript

oop

what's the difference in the construction of these two objects - apart from the privacy of the member variable ?

function A() { this.a = 99; }
A.prototype.setA = function(newVal) { this.a = newVal; }
A.prototype.getA = function({ return this.a; }

And this:

function A() {
   var a = 99;
   return {
      setA: function(newVal) { a=newVal; }
      getA: function() { return a; }
   }
}

I'm not interested in the privacy of the member variable so much as the way the functions are defined.

Am I right in thinking that in the second version all objects created via new A() will get copies of the defined functions, where as in the first version all calls to the defined functions will go to the one and only prototype object (for the A object). Is this right?

If so does version 2 have any performance costs?

Also, Is one way preferred over another - or is there a better way again?

Many Thanks

like image 397
push 22 Avatar asked Dec 27 '22 14:12

push 22


1 Answers

Am I right in thinking that in the second version all objects created via new A() will get copies of the defined functions, where as in the first version all calls to the defined functions will go to the one and only prototype object (for the A object). Is this right?

Yes

If so does version 2 have any performance costs?

More memory usage with setA and getA per object A

Also, Is one way preferred over another - or is there a better way again?

Since you don't care about encapsulation, use prototype

like image 199
Joe Avatar answered Dec 30 '22 09:12

Joe