手机版
你好,游客 登录 注册
背景:
阅读新闻

浅谈JavaScript中的对象

[日期:2015-10-26] 来源:Linux社区  作者:zam151 [字体:大 中 小]

面向对象的开发:对象有自己的属性、对象具备自己的方法

JS中this关键字:指的是当前函数或者属性归属的对象。

                      在对象环境中,关键字this指的是调用对象。

                      在函数调用中,关键字this可以用来设置对象属性。

一、类

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

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 }

大话设计模式(带目录完整版) PDF+源代码  http://www.linuxidc.com/Linux/2014-08/105152.htm

JavaScript设计模式 中文清晰扫描版PDF  http://www.linuxidc.com/Linux/2015-09/122725.htm

浅谈JavaScript中的对象  http://www.linuxidc.com/Linux/2015-10/124067.htm

本文永久更新链接地址:http://www.linuxidc.com/Linux/2015-10/124517.htm

linux
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款