Drawback of creating true private method
suggest changeA closure used as a private method is a new function object on every instance, so many instances cost more memory than a method shared on the prototype. Class # methods do not have that per-instance copy.
function contact(first, last) {
this.firstName = first;
this.lastName = last;
// private method
var formatPhoneNumber = function(number) {
// format phone number based on input
};
// public method
this.setMobileNumber = function(number) {
this.mobile = formatPhoneNumber(number);
};
}
Each instance has its own formatPhoneNumber function:
var rob = new contact('Rob', 'Sanderson');
var don = new contact('Donald', 'Trump');
var andy = new contact('Andy', 'Whitehall');
Prefer a prototype method, or a class # method, unless the function must close over constructor variables.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents