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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With