什麼是物件?
在 JavaScript 中,物件 (Object) 是一種用來儲存資料和描述行為的結構。物件可以包含屬性 (Attributes) 和方法 (Methods)。屬性是用來儲存資料的,而方法則是用來執行動作的。
舉個例子,我們可以將一個人描述為一個物件,這個物件包含以下資訊:
- 屬性:名字、年齡、身高、體重等,屬於資料。
- 方法:走路、跑步、吃飯、睡覺等,屬於行為。
如何建立物件?
在 JavaScript 中,我們可以使用物件語法來建立物件:const 變數名稱 = { 屬性A: 值, 屬性B: 值, 屬性C: 值 },值的內容可以是任何資料類型,包括數字、字串、布林值、陣列、函式等,甚至是物件。
以下是一個描述人的物件範例:
javascript
const person = {
name: 'Aaron', // 屬性
age: 30,
height: 170,
weight: 70,
walk: function () {
console.log(`${this.name} is walking`); // 方法
},
eat: function () {
console.log(`${this.name} is eating`);
},
};
console.log(person.name); // 輸出 "Aaron"
person.walk(); // 輸出 "Aaron is walking"
person.eat(); // 輸出 "Aaron is eating"類別與物件
當我們需要建立多個相似的物件時,可以使用 類別 (Class) 作為模板。
類別可以幫助我們快速建立具有相同屬性和方法的物件,並提高程式碼的重用性。
使用類別建立物件
以下是一個使用類別建立物件的範例:
javascript
class Person {
// 類別的建構子,在建立物件時會被呼叫
constructor(name, age, height, weight) {
this.name = name; // 初始化屬性
this.age = age;
this.height = height;
this.weight = weight;
}
walk() {
console.log(`${this.name} is walking`);
}
eat() {
console.log(`${this.name} is eating`);
}
}
// 使用類別建立物件
const aaron = new Person('Aaron', 30, 170, 70); // new Person() 會呼叫 constructor
aaron.walk(); // 輸出 "Aaron is walking"
aaron.eat(); // 輸出 "Aaron is eating"
const tina = new Person('Tina', 25, 160, 50); // new Person() 會呼叫 constructor
tina.walk(); // 輸出 "Tina is walking"
tina.eat(); // 輸出 "Tina is eating"this 的概念
在物件的方法中,this 關鍵字代表當前物件的實例。它可以用來存取物件的屬性和方法。
範例
javascript
const person = {
name: 'Aaron',
sayHello: function () {
console.log(`Hello, my name is ${this.name}`);
},
};
person.sayHello(); // 輸出 "Hello, my name is Aaron"繼承 (Inheritance)
繼承是一種讓子類別 (Subclass) 繼承父類別 (Parent Class) 屬性和方法的機制。這樣可以讓程式碼更具重用性。
範例
javascript
// 定義一個父類別 Shape 作為基底類別
class Shape {
constructor(name) {
this.name = name;
}
describe() {
console.log(`This is a ${this.name}`);
}
area() {
console.log('Area calculation is not implemented for this shape');
}
}
// 定義子類別 Triangle
class Triangle extends Shape {
constructor(base, height) {
super('Triangle');
this.base = base;
this.height = height;
}
// 覆寫 area 方法
area() {
return (this.base * this.height) / 2;
}
}
// 定義子類別 Rectangle
class Rectangle extends Shape {
constructor(width, height) {
super('Rectangle');
this.width = width;
this.height = height;
}
// 覆寫 area 方法
area() {
return this.width * this.height;
}
}
// 定義子類別 Circle
class Circle extends Shape {
constructor(radius) {
super('Circle');
this.radius = radius;
}
// 覆寫 area 方法
area() {
return Math.PI * this.radius ** 2;
}
}
// 測試
const triangle = new Triangle(10, 5);
triangle.describe(); // 輸出 "This is a Triangle"
console.log(`Area: ${triangle.area()}`); // 輸出 "Area: 25"
const rectangle = new Rectangle(10, 5);
rectangle.describe(); // 輸出 "This is a Rectangle"
console.log(`Area: ${rectangle.area()}`); // 輸出 "Area: 50"
const circle = new Circle(7);
circle.describe(); // 輸出 "This is a Circle"
console.log(`Area: ${circle.area().toFixed(2)}`); // 輸出 "Area: 153.94"物件解構
物件解構 (Object Destructuring) 是一種方便的語法,可以讓我們從物件中取出特定屬性,並將其指派給變數。
範例
javascript
const person = {
name: 'Aaron',
age: 30,
height: 170,
weight: 70,
};
// 物件解構
const { name, age } = person;
console.log(name); // 輸出 "Aaron"
console.log(age); // 輸出 30Function 也是一種物件
在 JavaScript 中,函式 (Function) 本質上也是一種物件。我們可以將函式指派給變數,並將其當作物件來使用。
範例
javascript
// 定義一個函式
function greet(name) {
return `Hello, ${name}!`;
}
greet.message = 'Welcome to JavaScript!'; // 在函式上新增屬性
console.log(greet.message); // 輸出 "Welcome to JavaScript!"甚至可以將函式當作物件來進行建構,例如:
javascript
// 定義一個函式
function person() {
this.name = 'Aaron';
this.age = 30;
this.height = 170;
this.weight = 70;
}
// 建立一個 person 物件
const aaron = new person();
console.log(aaron.name); // 輸出 "Aaron"
console.log(aaron.age); // 輸出 30
console.log(aaron.height); // 輸出 170
console.log(aaron.weight); // 輸出 70範例練習
試著完成以下程式碼,並預測每一行的輸出結果:
javascript
// 定義一個類別
class Car {
constructor(brand, model, year) {
this.brand = brand;
this.model = model;
this.year = year;
}
start() {
console.log(`${this.brand} ${this.model} is starting`);
}
drive() {
console.log(`${this.brand} ${this.model} is driving`);
}
}
// 建立兩個車輛物件
const car1 = new Car('Toyota', 'Corolla', 2020);
const car2 = new Car('Tesla', 'Model 3', 2022);
// 呼叫方法
car1.start(); // 輸出什麼?
car1.drive(); // 輸出什麼?
car2.start(); // 輸出什麼?
car2.drive(); // 輸出什麼?練習目標
- 嘗試在你的程式編輯器中執行這段程式碼。
- 新增一個方法,例如
stop(),讓車輛停止,並測試它的行為。 - 嘗試新增一個子類別,例如
ElectricCar,並為其新增特有的方法,例如charge()。
透過這些練習,你將能夠更好地理解物件的概念、類別的使用以及繼承的應用!
練習區
步驟 1: 建立一個新的檔案
- 在你的專案資料夾中,建立一個名為
object-practice.js的檔案。
步驟 2: 撰寫以下練習
在 object-practice.js 中完成以下練習:
- 建立一個物件
person,包含name,age, 和hobby屬性。 - 新增一個方法
introduce到person,輸出 "Hi, my name is [name], I am [age] years old and I like [hobby]!"。 - 呼叫
introduce方法並檢查輸出。 - 嘗試新增一個新的屬性
job並設定值,然後輸出整個物件。
步驟 3: 執行檔案
- 在終端機中執行
node object-practice.js,檢查結果是否正確。
