物件導向程式設計 (Object-oriented programming, OOP) 是一種使用 abstraction 概念的程式設計方式,由先前所建立的技術所組成:
JavaScript 是一個以雛型為基礎 (Prototype-based) 的程式設計語言 -> 物件導向程式設計
JavaScript 透過函數來當類別的建構子,但無類別敘述 -> 與其他物件導向程式設計的差異
**創立一個物件 1 **
// Object literal
// empty
var city = {};
// with properties
var book = {
title: 'JavaScript',
price: 150,
publish: 1990,
category: ['Science fiction', 'adventure'],
isOnSale: false
};
點記法 (Dot notation)
透過 . 存取物件的屬性與函式
book.title; // output JavaScript
book.category; // output ['Science fiction', 'adventure']
book.category[1]; // output adventure
括弧記法 (Bracket notation)
透過 [] 存取物件的屬性與函式
book['title']; // output JavaScript
book['category']; // output ['Science fiction', 'adventure']
book['category'][1]; // output adventure
創立一個物件 2
// new Object
var book = new Object();
book.title = JavaScript;
book.price = 150;
book['category'] = ['Science fiction', 'adventure'];
Objects and methods
在物件裡寫 methods -> 並透過 this 指向進行寫值、計算
// basic
var book = {
title: 'JavaScript',
price: 150,
publish: 1990,
category: ['Science fiction', 'adventure'],
isOnSale: false,
countYear: function(publish){
return 2020 - publish;
}
};
console.log(book.countYear(1990)); // 30
//get variable by this
var book = {
title: 'JavaScript',
price: 150,
publish: 1990,
category: ['Science fiction', 'adventure'],
isOnSale: false,
countYear: function() {
this.age = 2020 - this.publish;
}
};
book.countYear();
book.age; // output 30 -> 寫入成功!
課程 : https://www.udemy.com/course/the-complete-javascript-course/
來源 :
https://pjchender.blogspot.com/2016/01/javascriptobject.html
https://developer.mozilla.org/zh-TW/docs/Learn/JavaScript/Objects/Basics
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Introduction_to_Object-Oriented_JavaScript