Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

@Gozala 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