穷小子

MajorYe
数据加载中……
object.property与object["property"]的区别
刚吃完饭,也没啥事干,来写写blog吧
也许就像你看到的那样,我写的东西是比较偏的
先来举个例子吧:
>>> 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 阅读(363) 评论(1)  编辑  收藏 所属分类: WEB开发

评论

# re: object.property与object["property"]的区别 2008-04-23 13:56 fuyongjie

叶师兄:近来可好?
太巧了,一中午正在研究firebug咋调试Js呢,这不正好就给碰上了。一下子就给入门了,哈哈哈

  回复  更多评论    

只有注册用户登录后才能发表评论。


网站导航: