Skip to content

Instantly share code, notes, and snippets.

@Ugarz
Last active October 25, 2018 08:54
Show Gist options
  • Save Ugarz/8c8922ca3af7d748de68137ec134bd6d to your computer and use it in GitHub Desktop.
Save Ugarz/8c8922ca3af7d748de68137ec134bd6d to your computer and use it in GitHub Desktop.
Javscript Functions and privacy

Javascript Functions and privacy

Using Closures

Douglas Crockford’s code conventions for JavaScript recommend this pattern when privacy is important discouraging naming properties with the underscore prefix to indicate privacy.

var Person = (function() {
    function Person(name) {
        this.getName = function() {
            return name;
        };
    }

    return Person;
}());

var p = new Person('John');

print('Person 2 name: ' + p.getName());
// Person 2 name: John

delete p.name;

print('Person 2 name: ' + p.getName() + ' stays private.');
// Person 2 name: John stays private.

Using Symbols

Symbols are ES6 feature See compatibility supports here

var Person = (function() {
    var nameSymbol = Symbol('name');

    function Person(name) {
        this[nameSymbol] = name;
    }

    Person.prototype.getName = function() {
        return this[nameSymbol];
    };

    return Person;
}());

var p = new Person('John');

print('Person 3 name: ' + p.getName());
// Person 3 name: John

delete p.name;

print('Person 3 name: ' + p.getName() + ' — stays private.');
// Person 3 name: John — stays private.

print('Person 3 properties: ' + Object.getOwnPropertyNames(p));
// Person 3 properties: 

Resources

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment