Skip to content

Instantly share code, notes, and snippets.

@kriskowal
Created March 16, 2012 00:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kriskowal/2047799 to your computer and use it in GitHub Desktop.
Save kriskowal/2047799 to your computer and use it in GitHub Desktop.
Prototypical name spaces with WeakMap
function Namespace(common) {
var map = WeakMap();
common = common || null;
function ns(object) {
if (Object(object) !== object)
return common;
if (!map.has(object)) {
var prototype = Object.getPrototypeOf(object);
map.set(object, Object.create(ns(prototype)));
}
return map.get(object);
}
return ns;
}
var private = Namespace({
greet: function () {
console.log("Hello, " + this.name + "!");
}
});
var parent = {};
var child = Object.create(parent);
private(parent).name = "World";
private(parent).greet();
private(child).greet();
console.log('parent:', parent); // {}
console.log('child:', child); // {}
console.log('child.__proto__ === parent:', Object.getPrototypeOf(child) === parent); // true
console.log('private(parent):', private(parent)); // {name: "World"}
console.log('private(child).__proto__:', Object.getPrototypeOf(private(child))); // {name: "World"}
console.log('private(child).__proto__ === private(parent):', Object.getPrototypeOf(private(child)) === private(parent)); // true
@Gozala
Copy link

Gozala commented Mar 16, 2012

Nice! In fact I thought about this solution as soon as I published this post :)
mozilla/addon-sdk#375

Have not thought of common though, I may incorporate it in that pull request.

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