I have class
function Foo(a) {
this.a = a;
this.bar = function () {
console.log(this.a);
};
this.buz = function () {
this.a();
console.log('bzz');
};
}
and I'll have quite many instances of this class. Should I move methods to prototype?
function Foo(a) {
this.a = a;
}
Foo.prototype = {
bar: function () {
console.log(this.a);
},
buz: function () {
this.a();
console.log('bzz');
}
}
Yes. This will save on memory as each method will be shared instead of recreated each time you instantiate the class.
Methods inside the constructor are considered privileged methods as they can have access to private variables inside the constructor and should only be used if you need access to a private variable.
Crockford on privileged methods
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