On Jan 26, 9:35 pm, "Ray" <ray_use...@yahoo.comwrote:
Quote:
Hello,
>
I'm reading Mr. Flanagan's JS Definitive Guide 5th edition. I was
wondering about a point he make in section 10.2 of the book: "Importing
Symbols from Namespaces".
>
He mentions in there that one can create an alias for the symbol
defined in a namespace like this:
>
// This is an easier name, to save typing.
var define = com.davidflanagan.Class.define;
>
Another way of doing it, again from the same section, is discussed
next:
>
// Create a simple namespace. No error checking required. The
// module user knows that this symbol does not exist yet.
var Class = {};
// Now import a symbol into this new namespace.
Class.define = com.davidflanagan.Class.define;
>
Now my question is: what's wrong with aliasing the namespace itself?
E.g.:
>
var cls = com.davidflanagan.Class;
cls.define();
>
Why does he need to create a new simple namespace and import the symbol
from one namespace to another? Am I missing something really obvious
here?
It looks like he wants to protect the original namespace. For example
var com = {davidflanagan:{Class:{}}};
com.davidflanagan.Class.foo = function() {alert('foo');};
var cls = com.davidflanagan.Class;
cls.foo = function(){alert('bar');};
com.davidflanagan.Class.foo(); // shows "bar" but maybe should be
"foo"
with Flanagan's importing system
var com = {davidflanagan:{Class:{}}};
com.davidflanagan.Class.foo = function() {alert('foo');};
var cls = {};
cls.foo = com.davidflanagan.Class.foo; // import one symbol
cls.foo = function(){alert('bar')}; // subsequently change it in the
new namespace
com.davidflanagan.Class.foo(); // shows "foo", so original namespace
not affected.
I'm just guessing on his intent.
Peter