1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000 1.2 +++ b/addon-sdk/source/lib/sdk/core/namespace.js Wed Dec 31 06:09:35 2014 +0100 1.3 @@ -0,0 +1,43 @@ 1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public 1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this 1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ 1.7 + 1.8 +"use strict"; 1.9 + 1.10 +module.metadata = { 1.11 + "stability": "unstable" 1.12 +}; 1.13 + 1.14 +const create = Object.create; 1.15 +const prototypeOf = Object.getPrototypeOf; 1.16 + 1.17 +/** 1.18 + * Returns a new namespace, function that may can be used to access an 1.19 + * namespaced object of the argument argument. Namespaced object are associated 1.20 + * with owner objects via weak references. Namespaced objects inherit from the 1.21 + * owners ancestor namespaced object. If owner's ancestor is `null` then 1.22 + * namespaced object inherits from given `prototype`. Namespaces can be used 1.23 + * to define internal APIs that can be shared via enclosing `namespace` 1.24 + * function. 1.25 + * @examples 1.26 + * const internals = ns(); 1.27 + * internals(object).secret = secret; 1.28 + */ 1.29 +function ns() { 1.30 + const map = new WeakMap(); 1.31 + return function namespace(target) { 1.32 + if (!target) // If `target` is not an object return `target` itself. 1.33 + return target; 1.34 + // If target has no namespaced object yet, create one that inherits from 1.35 + // the target prototype's namespaced object. 1.36 + if (!map.has(target)) 1.37 + map.set(target, create(namespace(prototypeOf(target) || null))); 1.38 + 1.39 + return map.get(target); 1.40 + }; 1.41 +}; 1.42 + 1.43 +// `Namespace` is a e4x function in the scope, so we export the function also as 1.44 +// `ns` as alias to avoid clashing. 1.45 +exports.ns = ns; 1.46 +exports.Namespace = ns;