讲解一下JavaScript中的对象

我们知道生活中客观存在的一切事物皆为对象,那在程序中的对象是什么样子呢?我们可以将程序中的对象理解为客户端世界中的对象在一种计算机中的一种表示方式.所有的编程语言中提到的对象其性质都是类似的,它往往对应内存中的一块区域,在这个区域中存储对象的属性或方法信息。

一、类

在面向对象编程中,对象是一个类的实例,类定义了一组公开的属性和方法。类简化了同一类型的多个对象的创建。

1 var star = {}; //组装一个star对象 2 star[“Polaris”] = new Object; 3 star[“Mizar”] = new Object; 4 star[“Polaris”].constellation = “Ursa Minor”; 5 star[“Mizar”].constellation = “Ursa Major”;

以下为使用伪类组装一个star对象:【主要目的是:简化代码重复率,提高阅读效率】

1 var star = {};
2 function Star(constell,type,specclass,magnitude) {
3  this.constellation = constell;
4  this.type = type;
5  this.spectralClass = specclass;
6  this.mag = magnitude;
7 }
8
9 star["Polaris"] = new Star("Ursa Minor","Double/Cepheid","F7",2.0);
10 star["Mizar"] = new Star("Ursa Major","Spectroscopic Binary","A1 V",2.3);

二、创建对象

2.1 两种方法创建对象:

1 var star=new Object; //new关键字
2 var star={}      //花括号

2.2 为对象添加属性

1 star.name="Polaris";
2 star.constellation="Ursa Minor";

2.3 遍历对象属性 用for…in..函数

1 function Star(constell,type,specclass,magnitude) {
2    this.constellation = constell;
3    this.type = type;
4    this.spectralClass = specclass;
5    this.mag = magnitude;
6  }
7  star["Polaris"] = new Star("Ursa Minor","Double/Cepheid","F7",2.0);
8  star["Mizar"] = new Star("Ursa Major","Spectroscopic Binary","A1 V",2.3);
9  star["Aldebaran"] = new Star("Taurus","Irregular Variable","K5 III",0.85);
10  star["Rigel"] = new Star("Orion","Supergiant with Companion","B8 Ia",0.12);
11
12 for (var element in star) {             //元素名
13  for (var propt in star[element]) {       //属性值
14    alert(element + ": " + propt + " = " + star[element][propt]);
15  }
16 }

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值