2012-02-15 56 views
1

如果我聲明一個對象如下:我需要更好地理解JavaScript的基本性質對象

var foo.bar = new Object; 

這是否自動使富的對象?如果沒有,我想這兩個foo和foo.bar是對象,我需要使用下面的代碼:

var foo = new Object; 
var foo.bar = new Object; 

如果我創建如上這兩個對象,是有他們之間或父/子關係他們是完全獨立的實體嗎?

對於我的問題的簡單性,我表示歉意,但我正在努力更全面地理解數據的各種構造方式。

+0

感謝所有爲你的答案,尤其是對於正確的文字符號來使用。 – WyoBuckeye 2012-02-15 16:06:17

回答

3

If I declare an object as follows:

var foo.bar = new Object; 

Does that automatically make foo an object?

不是。這是一個語法錯誤;

SyntaxError: Unexpected token .

If not and I want both foo and foo.bar to be objects do I need to use the following code:

var foo = new Object; 
var foo.bar = new Object; 

不,那是又一個語法錯誤。你應該使用。

var foo = new Object; 
foo.bar = new Object; 

但是現在使用object literal syntax這些日子更爲常見;

var foo = { 
    bar: { 

    } 
} 

And if I create these two objects as above, is there a parent/child relationship between them or are they completely separate entities?

他們是完全獨立的實體。它們之間的唯一聯繫是foo持有對bar的引用。其他的東西可以很容易地引用酒吧;

var baz = foo.bar; 
// Now baz and foo.bar are both pointing to the same object 

alert(baz === foo.bar); // true; 
baz.attr = 1; 
alert(baz.attr); // 1 
alert(foo.bar.attr); // 1 

delete foo.bar; // delete foo's reference to bar 
alert(baz.attr); // still shows 1 
alert(foo.bar.attr); // error, because we deleted `bar`. 

Try it yourself... http://jsfiddle.net/AMXLE/1

0

這第一個例子將導致一個錯誤,因爲foo以前沒有定義的,但你可以做什麼,是使用對象文本:

var foo = { bar: new Object() }; 

甚至:

var foo = { bar: {} }; 

在條款您的最後一個問題,bar成爲foo的財產。

+0

事實上,文字是更可取的 – 2012-02-15 15:54:26

+2

它不會錯誤,因爲'foo'尚未定義(事實上,它已在OP的例子中定義);它會拋出一個'SyntaxError',因爲'.'字符在JavaScript變量名中是無效的。 – 2012-02-15 15:54:56

+0

只應該是'var foo = {bar:{}};'因爲'{}'和'new Object()'是一樣的。 – zzzzBov 2012-02-15 15:55:09

2
var foo.bar = new Object; 

這會拋出一個SyntaxError; JavaScript變量名稱中不允許使用.字符。這會工作,但:

var foobar = new Object; 

var foo = new Object; var foo.bar = new Object;

這不會出於同樣的原因像以前一樣工作。使用這個來代替:

// using the `Object` constructor 
var foo = new Object; 
foo.bar = new Object; 

// or just use an object literal: 
var foo = { 
    'bar': {} 
}; 

And if I create these two objects as above, is there a parent/child relationship between them or are they completely separate entities?

兩個barfoo都是對象,但barfoo屬性。

0

我喜歡看到它的方式,是在Javascript對象是完全一樣的關聯數組(又名哈希表,又名字典),其中每個鍵是一個字符串,並且每個值可以是任何類型的,包括function。所以,你的代碼是EXACTLY一樣:

var foo = {}; 
foo["bar"] = {}; 

甚至:

var foo = {"bar": {}};