DAY 25
0
Modern Web

## 淺談物件導向程式設計 Object-oriented programming

1. 屬性：靜態的資料，用於描述物件的狀態
2. 方法：物件的功能（函式），或說物件的行為

``````const hero = {
id: 'Batman',
name: ['Bruce', 'Wayne'],
gender: 'Male',
age: 41,
greet: function () {
console.log(`Hello! I am \${this.name[0]}`)
}, // this 代表「誰呼叫了這個函式」，在這指 hero
run: function () {
return 'run!!!'
},
punch: function () {
return 'One Punch!!!'
},
beat: function () {
return 'Beat it!!!'
}
}

// 方法
hero.greet()
hero.run()
hero.punch()
hero.beat()
``````

### Constructor Function 建構式函式

``````function Hero (name, title, studio) {
this.name = name
this.title = title
this.studio = studio
}
``````

``````let onePunchMan = new Hero('Saitama', 'One-Punch Man', 'Madhouse')

let batman = new Hero('Bruce Wayne', 'Dark Knight', 'DC')

let wolverine = new Hero('Logan', 'Wolverine', 'Marvel')
``````

### Constructor Prototype 物件原型

``````Hero.prototype.attack = function(skill) {
console.log(`\${this.title} attack with \${skill}`)
}
``````

``````onePunchMan.attack('Normal Punch.')
// One-Punch Man attack with Normal Punch.

onePunchMan.attack('Serious Punch!')
// One-Punch Man attack with Serious Punch!
``````

### JavaScript 中的物件導向程式設計

• `num` 的 prototype 就是 `Number`

• 而它的 constructor function 長這樣：

• `Number` 又源自 `Object``Object` 就沒有上一層的原型了 `null`