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

1

3 Answers 3

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'
    }
} 
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

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.

1 Comment

thanks!how can js allow to root.person = []; and not root.prototype.person = [];?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.