歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 淺談JavaScript中的對象

淺談JavaScript中的對象

日期:2017/3/1 9:21:14   编辑:Linux編程

面向對象的開發:對象有自己的屬性、對象具備自己的方法

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

Copyright © Linux教程網 All Rights Reserved