Created
March 16, 2012 00:14
-
-
Save kriskowal/2047799 to your computer and use it in GitHub Desktop.
Prototypical name spaces with WeakMap
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
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.