JavaScript 支援物件導向概念,包括封裝、聚合、繼承與多型。物件由屬性與方法組成,屬性是資料,方法則是附加在物件上的函式。
const employee = new Object();
employee.name = 'Jack';
employee.age = 30;
console.log(employee.name);
function book(title, author) {
this.title = title;
this.author = author;
}
const myBook = new book('Perl', 'Mohtashim');
console.log(myBook.title);
console.log(myBook.author);
function addPrice(amount) {
this.price = amount;
}
function book(title, author) {
this.title = title;
this.author = author;
this.addPrice = addPrice;
}
const myBook = new book('Perl', 'Mohtashim');
myBook.addPrice(100);
console.log(myBook.price);
with 可簡化物件屬性存取,但在嚴格模式與現代開發中不建議使用,容易降低可讀性與除錯效率。