简体   繁体   English

命名空间树JavaScript示例和语法说明

[英]Namespaces tree javascript example and explanation of syntax

Namespaces tree javascript example and explanation of syntax. 命名空间树javascript示例和语法说明。

This namespaces to be defined in javascript: 此名称空间将在javascript中定义:

  1. root

  2. root.person root.person

  3. root.home root.home

  4. root.home.relative 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 请解释您的代码,我对php / c / java不太了解js

Thanks 谢谢

JavaScript has no concept of "namespaces" in the sense of Java etc. Instead we use good old objects, and add attributes to those objects. JavaScript没有Java等意义上的“命名空间”概念。相反,我们使用好的旧对象,并向这些对象添加属性。

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"). 如果root是您的“ 名称空间 ”,我们将root定义为一个对象,并将名称空间的成员定义为该对象上的成员 (“ person”,“ home”,“ relative”)。

To declare an object (for root ), the easiest way is to use object literal syntax 要声明一个对象(对于root ),最简单的方法是使用对象文字语法

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

You can nest objects using this syntax as follows (to achieve your nested relative object: 您可以使用以下语法嵌套对象(以实现嵌套的relative对象:

var root = {
    person: {
        'first_name': 'Matt',
        'last_name': 'Smith'
    },
    home: {
        relative: 'Frank'
    }
} 

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 = {}; 如果要动态地给对象提供额外的属性,而不是仅给一个值,请将其声明为空对象文字var obj = {}; obj.subObj = {}; var obj = {}; obj.subObj = {}; etc etc. 等等等

If your question is what you are doing wrong.. You need to define your name space as following 如果您的问题是您在做什么错..您需要按以下方式定义名称空间

var root = {};
root.person = {}; 

There is already quite a detailed Stackoverflow answer to this topic How do I declare a namespace in JavaScript? 关于该主题的Stackoverflow答案已经非常详细了, 如何在JavaScript中声明名称空间? and I suggest you look there for more help. 我建议您到那里寻求更多帮助。

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. 如果您使用的是Firebug, console.log将漂亮地打印您的对象层次结构。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM