0

Namespaces tree javascript example and explanation of syntax.

This namespaces to be defined in javascript:

  1. root

  2. root.person

  3. root.home

  4. root.home.relative

my try that wrong:

var root='';
root.person='';
root.home='';
root.home.relative='';

Please explain your code I not know js well as php/c/java

Thanks

tomy
  • 1
  • 1
  • Probably better answered by reading through: http://stackoverflow.com/questions/881515/javascript-namespace-declaration as AlexJones mentioned below. – Kzqai Aug 22 '11 at 16:15

3 Answers3

3

JavaScript has no concept of "namespaces" in the sense of Java etc. Instead we use good old objects, and add attributes to those objects.

If root is to be your "namespace", we define root as an object, and define the members of the namespace as members on the object ("person", "home", "relative").

To declare an object (for root), the easiest way is to use object literal syntax

var root = {
    person: 'Jim',
    home: 'London'
}

You can nest objects using this syntax as follows (to achieve your nested relative object:

var root = {
    person: {
        'first_name': 'Matt',
        'last_name': 'Smith'
    },
    home: {
        relative: 'Frank'
    }
} 
Matt
  • 74,352
  • 26
  • 153
  • 180
1

Not sure I totally understand what you after, but do you mean this:

var root = {};
root.person = '';
root.home = {};
root.home.relative = '';

If you want to give an object extra properties dynamically, rather than just one value, declare it as an empty object literal var obj = {}; obj.subObj = {}; etc etc.

DaveRandom
  • 87,921
  • 11
  • 154
  • 174
0

If you want to nest properties, make the variable an object, not just a string:

var root = {};
root.person = '';
root.home = {};
root.home.relative = '';
console.log(root);

If you're using Firebug, the console.log will pretty-print your object hierarchy.

wsanville
  • 37,158
  • 8
  • 76
  • 101