What is Ext.namespace, how should we use them?
extjs, extjs4.2, javascript, namespaces
Solution
First off, this is what `Ext.ns('Company.data')` is roughly equivalent too:
if (!Company) var Company = {};
if (!Company.Data) Company.Data = {};
Basically, it is just a shortcut for defining deeply nested structures of objects. It is useful if your project structures this way; I've seen projects with a Java backend that duplicate the `com.company.app.data.package` package names in JavaScript, for which `Ext.ns` is a nice shortcut.
Addressing your questions point by point:
- If I have `Ext.namespace('Company', 'Company.data')` at the top of my JS page, does this mean that it carries all the other function name and variables (like a global scope)?
No. You have to add to `Company.Data`, like `Company.Data.newVal = 5;`.
- What exactly 'Company' and 'Company.data' stand for in `Ext.namespace('Company', 'Company.data')`?
They are names, chosen by you, following your projects convention.
- Why new convention `Ext.ns('Company.data')` does not have 'Company' like in `Ext.namespace`?
Because 'Company' is implied. That is, `Ext.ns('Company', 'Company.data')` is like:
if (!Company) var Company = {};
if (!Company) var Company = {};
if (!Company.Data) Company.Data = {};
This makes it easier to see why the first 'Company' is redundant.
What does this mean `Specifying the last node of a namespace implicitly creates all other nodes`?
When exactly this idea should be used?
I answered these two above.
Problem
I came across to `Ext.namespace()` in the project that I am working on. I looked in Sencha's website and the explanation was not very helpful. This is what they are saying: Creates namespaces to be used for scoping variables and classes so that they are not global. Specifying the last node of a namespace implicitly creates all other nodes. ``` Ext.namespace('Company', 'Company.data'); ``` They also mention that `Ext.ns('Company.data')` is preferable. I apologize if this question seems simple or dumb, but I really want to completely understand this concept. Thanks in advance This is what is not very clear to me: - If I have `Ext.namespace('Company', 'Company.data')` at the top of my JS page, does this mean that it carries all the other function name and variables (like a global scope)? - What exactly 'Company' and 'Company.data' stand for in `Ext.namespace('Company', 'Company.data')`? - Why new convention `Ext.ns('Company.data')` does not have 'Company' like in `Ext.namespace`? - What does this mean `Specifying the last node of a namespace implicitly creates all other nodes`? - When exactly this idea should be used?