object.property與object["property"]的區別
也許就像你看到的那樣,我寫的東西是比較偏的
先來舉個例子吧:
>>> var person=function(){}
>>> person.aa="aa"
"aa"
>>> person.bb="bb"
"bb"
>>> person.cc="cc"
"cc"
上面是定義了一個person類
給這個類添加了幾個類屬性
你單獨運行
>>> person.cc
"cc"
那是沒問題的
但是你在程序中寫就有問題了,
看看下面的程序:
for(var t in person){
alert(t);
alert(person.t) //為什么這個就有問題呢,結果為undefined
}
但該為
for(var t in person){
alert(t);
alert(person.[t]) //這樣就可以了
}
為什么呢????
The important difference to note between these two syntaxes is that in the first, the property name is an identifier, and in the second, the property name is a string. You'll see why this is so important shortly.
In C, C++, Java, and similar strongly typed languages, an object can have only a fixed number of properties, and the names of these properties must be defined in advance. Since JavaScript is a loosely typed language, this rule does not apply: a program can create any number of properties in any object. When you use the . operator to access a property of an object, however, the name of the property is expressed as an identifier. Identifiers must be typed literally into your JavaScript program; they are not a datatype, so they cannot be manipulated by the program.
On the other hand, when you access a property of an object with the [] array notation, the name of the property is expressed as a string. Strings are JavaScript datatypes, so they can be manipulated and created while a program is running.
還沒寫完,待我醒來再細說!
posted on 2008-04-21 12:19 MajorYe 閱讀(382) 評論(1) 編輯 收藏 所屬分類: WEB開發