Drawback of creating true private method

suggest change

A 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.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents