Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Private members in javascript

Tags:

javascript

Can anyone please tell me how do we use or declare private members in javascript.I will appreciate an example.I am new to this

like image 986
Android Help Avatar asked Dec 09 '22 18:12

Android Help


1 Answers

Douglas Crockford has a write-up on Private Members:

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.

function Container(param) {

    function dec() {
        if (secret > 0) {
            secret -= 1;
            return true;
        } else {
            return false;
        }
    }

    this.member = param;
    var secret = 3;
    var that = this;
}

The private method dec examines the secret instance variable. If it is greater than zero, it decrements secret and returns true. Otherwise it returns false. It can be used to make this object limited to three uses.

By convention, we make a private that variable. 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.

like image 53
Robert Avatar answered Dec 11 '22 07:12

Robert