Skip to content

Instantly share code, notes, and snippets.

@kevincennis
Created February 4, 2015 04:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kevincennis/19b0aacb6adb6dc8cf1d to your computer and use it in GitHub Desktop.
Save kevincennis/19b0aacb6adb6dc8cf1d to your computer and use it in GitHub Desktop.
WeakMap privacy
var User = (function() {
var cache = new WeakMap();
function User( name ) {
cache.set( this, {} );
this.name = name;
}
User.prototype = {
set password( password ) {
cache.get( this ).password = password;
},
auth: function( password ) {
return password === cache.get( this ).password;
}
};
return User;
}());
var user = new User('John');
user.password = 'P@ssw0rd!';
user.password; // undefined
user.auth('correcthorsebatterystaple'); // false
user.auth('P@ssw0rd!'); // true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment