在 JS 中,物件的屬性與方法本質上都是「值」,函式也是一等公民,可像變數一樣指派、傳遞、回傳。
var obj = new Object(); // 或 {}
obj["a"] = 1;
obj["b"] = "字串";
obj["c"] = false;
console.log(obj["a"]); // 1
console.log(obj.a); // 1,點號與中括號存取等價(鍵為合法識別碼時)
中括號語法支援變數鍵名、特殊字元鍵名,彈性極高。
var person = {
name: "小明",
age: 25,
isStudent: true,
greet: function() {
console.log("你好,我是 " + this.name);
},
// ES6 簡寫
sayHi() {
console.log(`Hi, I'm ${this.name}`);
}
};
person.greet(); // "你好,我是 小明"
person.sayHi(); // "Hi, I'm 小明"
// 方法也可解構指派給變數(但會丟失 this 綁定,需用 bind)
var fn = person.greet.bind(person);
fn();
function User(name, role) {
this.name = name;
this.role = role;
}
// 共用方法放在 prototype,節省記憶體
User.prototype.introduce = function() {
return this.name + " (" + this.role + ")";
};
var admin = new User("Admin", "管理員");
console.log(admin.introduce()); // "Admin (管理員)"
class Product {
constructor(id, name, price) {
this.id = id;
this.name = name;
this.price = price;
}
// 實例方法
getInfo() {
return `${this.name} - NT$${this.price}`;
}
// 靜態方法
static comparePrice(a, b) {
return a.price - b.price;
}
// Getter / Setter
get priceWithTax() {
return this.price * 1.05;
}
set priceWithTax(val) {
this.price = val / 1.05;
}
}
const p1 = new Product(1, "筆電", 30000);
console.log(p1.getInfo()); // "筆電 - NT$30000"
console.log(p1.priceWithTax); // 31500
Product.comparePrice(p1, p2); // 靜態方法呼叫
var config = {};
Object.defineProperty(config, "version", {
value: "1.0.0",
writable: false, // 唯讀
enumerable: true, // 可被 for...in 列舉
configurable: false // 無法刪除或重新定義
});
const PRIVATE = Symbol("internalId");
var obj = { [PRIVATE]: 123 };
console.log(obj[PRIVATE]); // 123,不會出現在 Object.keys() 中
var target = { count: 0 };
var handler = {
get(obj, prop) {
console.log(`讀取 ${prop}`);
return obj[prop];
},
set(obj, prop, value) {
console.log(`設定 ${prop} = ${value}`);
obj[prop] = value;
return true;
}
};
var proxy = new Proxy(target, handler);
proxy.count++; // 主控台輸出攔截日誌
| 場景 | 建議寫法 |
|---|---|
| 簡單資料結構、一次性物件 | 物件字面語法 {} |
| 需要建立多個相似實例 | ES6 class 或建構函式 |
| 需精確控制屬性行為(唯讀、不可列舉等) | Object.defineProperty |
| 動態鍵名、運行時決定結構 | 中括號語法 obj[key] = val |
| 框架/庫開發、需攔截操作 | Proxy |