Public, private and privileged methods in javascript

Original: Private Members in JavaScript by Douglas Crockford

Public

function Constructor(...) {
    this.membername = value;
}
Constructor.prototype.membername = value;

Private

function Constructor(...) {
    var that = this;
    var membername = value;
    function membername(...) {...}
}

Privileged

function Constructor(...) {
    this.membername = function (...) {...};
}

JavaScript is fundamentally about objects. Arrays are objects. Functions are objects. Objects are objects. Objects are collections of name-value pairs. The names are strings, and the values are strings, numbers, booleans, and objects (including arrays and functions). Objects are usually implemented as hashtables so values can be retrieved quickly.

If a value is a function, we can consider it a method. When a method of an object is invoked, the this variable is set to the object. The method can then access the instance variables through the this variable.

Objects can be produced by constructors, which are functions which initialize objects. Constructors provide the features that classes provide in other languages, including static variables and methods.

The members of an object are all public members. Any function can access, modify, or delete those members, or add new members.

Inside the constructor, the this keyword is used to add members to the object.

Private members are made by the constructor. Ordinary vars and parameters of the constructor becomes the private members:

function Container(param) {
    this.member = param;
    var secret = 3;
    var that = this;
}

This constructor makes three private instance variables: param, secret, and that. They are attached to the object, but they are not accessible to the outside, nor are they accessible to the object's own public methods. They are accessible to private methods. Private methods are inner functions of the constructor.

By convention, we make a private 'that' member. This is used to make the object available to the private methods. This is a workaround for an error in the ECMAScript Language Specification which causes this to be set incorrectly for inner functions.

Private methods cannot be called by public methods. To make private methods useful, we need to introduce a privileged method.

A privileged method is a public method that is able to access the private variables and methods. It is possible to delete or replace a privileged method, but it is not possible to alter it, or to force it to give up its secrets.

page_revision: 3, last_edited: 1224484658|%e %b %Y, %H:%M %Z (%O ago)
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License