-
-
Save jaandrle/8ce7f40202fb59b96f429ee15ea1b975 to your computer and use it in GitHub Desktop.
Privates and WeakMaps
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Based on a gist by @rwaldron | |
// https://gist.github.com/2897761 | |
function privatize() { | |
var map = new WeakMap(); | |
return function private(obj) { | |
var data = map.get(obj); | |
if (!data) { | |
map.set(obj, data = {}); | |
} | |
return data; | |
}; | |
} | |
var Person = (function () { | |
var private = privatize(); | |
function Person(name) { | |
private(this).name = name; | |
} | |
Person.prototype.say = function (msg) { | |
return private(this).name + ' says: ' + msg; | |
}; | |
return Person; | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment