Javascript的object”類似” C++或Java的class (說類似是因為它多了動態語言的特性,以及存取方式)
object擁有property和method(也可視為property)
例如一台車,它有馬力、重量以及啟動、煞車功能。 我們可以用一個object表示:
1 | var car = { // object使用{}宣告 |
Object也可以動態增加property:1
car.brand = "Toyota";
刪除property:1
delete car.brand;
Object也可以包含其它的object1
2
3
4var vehicle = {
Car: {horsePower: 300, weight: 2000},
Boat: {weight: 400000, height: 300000}
};
增加一method可動態新增object1
2
3
4
5
6
7
8
9var 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:1
2
3for (key in vehicle) { // key會存取vehicle內每個property
console.log(key); // 印出Car, Boat, addVehicle, Plane
}
參考資料:
object介紹