DIV CSS 佈局教程網

深入理解 JavaScript 物件、屬性與方法
編輯:JavaScript綜合知識     

物件導向基礎

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 關鍵字

with 可簡化物件屬性存取,但在嚴格模式與現代開發中不建議使用,容易降低可讀性與除錯效率。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved