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
sharedinstead of recreated each time you instantiate the class.Methods inside the constructor are considered
privileged methodsas they can have access toprivate variablesinside the constructor and should only be used if you need access to a private variable.Crockford on privileged methods