Namespacing properties is a great way to make a JavaScript library produce extendible objects. Namespacing in JavaScript can be done by prefixing namespace::
before object and property names. Unfortunately, namespacing is only supported in JavaScript 1.6 and higher, which is currently only implemented in SpiderMonkey (Firefox’s JavaScript engine) and Rhino with E4X enabled. Namespaces should have a toString method that returns a string of the same name (Foo.toString() == "Foo"
). In Firefox, the @mozilla.org/js/function
namespace (“function”) seems to be the default at which everything is under. For example, function::document == this.document
and x = "@mozilla.org/js/function"; x::document == function::document
. Also, anything with a blank string representation behaves the same way as long as it’s being used in a property, for example:
var foo = "@mozilla.org/js/function", bar = ""; try { // using try..catch because the error still fires in a typeof statement foo::document; // works fine bar::document; // error } catch(err if err instanceof ReferenceError) { // err.message == "reference to undefined XML name document"; } this.bar::document == this.document; |
The following example shows a naming conflict that can be solved using namespaced properties. In the examples, the fictional libraries, libSpaceTime and libDimensions are loaded. libDimensions adds a Size
global and creates a ‘dimensions’ setter on Object.prototype that accepts various inputs to change the width/height/depth/ect. of something. libSpaceTime introduces the SpaceTime
global. When a universe is created, the dimensions setter changes the number of dimensions the universe has. The width/height/ect. of a universe are automatically set (but can be changed) from the matter
property.
(more…)