1.1 对象
新对象由new操作符以及与其相伴的Object构造器产生。
var obj = new Object();
咋看一眼,JavaScript的Object 平淡无奇,一旦创建,它不持有任何数据,而且几乎不表现什么语意,似乎一切皆无----知道我们开始为它添加东西:我们称之为属性的东西。
1.1 对象的属性
var baoma = new object();
baoma.make = 'BMW';
baoma.model = 'Z';
baoma.year = 2012;
baoma.purchased = new Date(2012,2,22);
我们创建新的Object实例并且把他指派到名为baoma的变量。然后用几个不同类型的属性来填充这个变量:两个字符串,一个数字和一个Date类型的实例(Instance).
我们无需在复制之前声明这些属性,(这点和服务端的对象十分不同),这给与了JavaScript十分灵活的特性。
从示例中我们得知JavaScript Object 的示例(我们以后简称对象)是属性的集合,每一个属性都由名称和值构成。属性的名称是字符串,而属性的值可以是任何的JavaScript对象。这就使得Object实例的主要目的就是用作其他对象的已命名集合。这可能使你想起其他语言里的概念,例如Java里的映射,或其他语言里的字典或散列(hash)
在引用属性时,可以连续引用对象的属性。例如
var owner = new Object();
owner.name= 'Zhang San';
owner.occupation = 'programmer';
baoma.owner = owner;
可以使用的嵌套层次没有限制的(只要不超出常识的限度)。到目前为止,已完成的对象层次结构看起来如图一所示: