Alex Liang

[Javascript筆記] Object介紹

Javascript的object”類似” C++或Java的class (說類似是因為它多了動態語言的特性,以及存取方式)

object擁有property和method(也可視為property)

例如一台車,它有馬力、重量以及啟動、煞車功能。 我們可以用一個object表示:

car.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
var car = {			// object使用{}宣告
horsePower: 200,
weight: 4000,
start: function() {
alert("Start engine!");
},

break: function() {
alert("Break!");
}
};

console.log(car.horsePower); // 印出200
console.log(car["weight"]; // 也可以使用[]存取property

Object也可以動態增加property:

car.js
1
car.brand = "Toyota";

刪除property:

car.js
1
delete car.brand;

Object也可以包含其它的object

vehicle.js
1
2
3
4
var vehicle = {
Car: {horsePower: 300, weight: 2000},
Boat: {weight: 400000, height: 300000}
};

增加一method可動態新增object

vehicle.js
1
2
3
4
5
6
7
8
9
var vehicle = {
Car: {horsePower: 300, weight: 2000},
Boat: {horsePower: 400000, weight: 300000},
addVehicle: function(name, horsePower, weight) {
this[name] = {horsePower: horsePower, weight: weight}; // 使用this表示vehicle本體
}
};

vehicle.addVehicle("Plane", 600000, 8900000);

假如要計算vehicle內object的個數,需要用for-in loop:

vehicle.js
1
2
3
for (key in vehicle) {		// key會存取vehicle內每個property
console.log(key); // 印出Car, Boat, addVehicle, Plane
}

參考資料:
object介紹