---
# System prepended metadata

title: Eloquent JavaScript 3rd edition (2018) 第六章~The Secret Life of Objects
tags: [Javascript]

---

# Eloquent JavaScript 3rd edition (2018) 第六章~The Secret Life of Objects
---
tags: Javascript relate
---

###### tags: `Javascript`

> An abstract data type is realized by writing a special kind of program […] which defines the type in terms of the operations which can be performed on it.
> 
> Barbara Liskov, Programming with Abstract Data Types


這章節即將解釋OOP(object-oriented programming)在JS的應用

## Encapsulation(封裝形式)



> 一種將被擷取的函式介面的實作細節部份包裝、隱藏起來的方法。同時，它也是一種防止外界呼叫端，去存取物件內部實作細節的手段，這個手段是由程式語言本身來提供的。封裝被視為是物件導向的四項原則之一。


## Methods

Methods就是property裡面包含了function value以下是個很的例子:

這邊的speak就說明得很好

```javascript=
let rabbit = {};
rabbit.speak = function(line) {
  console.log(`The rabbit says '${line}'`);
};

rabbit.speak("I'm alive.");
// → The rabbit says 'I'm alive.'
```

`this` 可以自動地指向object被呼叫的地方

```javascript=

function speak(line) {
  console.log(`The ${this.type} rabbit says '${line}'`);
}
let whiteRabbit = {type: "white", speak};
let hungryRabbit = {type: "hungry", speak};

whiteRabbit.speak("Oh my ears and whiskers, " +
                  "how late it's getting!");
// → The white rabbit says 'Oh my ears and whiskers, how
//   late it's getting!'
hungryRabbit.speak("I could use a carrot right now.");
// → The hungry rabbit says 'I could use a carrot right now.'
```

`call` 如果你想要"更精確地"指向object被呼叫的地方可以使用

```javascript=
speak.call(hungryRabbit, "Burp!");
// → The hungry rabbit says 'Burp!'
```

## Prototypes

