tomy
tomy

Reputation: 1

Namespaces tree javascript example and explanation of syntax

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

Upvotes: 0

Views: 352

Answers (3)

Matt
Matt

Reputation: 75327

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'
    }
} 

Upvotes: 3

DaveRandom
DaveRandom

Reputation: 88707

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.

Upvotes: 1

wsanville
wsanville

Reputation: 37516

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.

Upvotes: 0

Related Questions