> For the complete documentation index, see [llms.txt](https://mistborn.gitbook.io/til-coding/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://mistborn.gitbook.io/til-coding/javascript/prototypal-inheritance.md).

# Prototypal inheritance

有 user 物件，當創造一個 admin 物件，想要 admin 有 user 物件的資料，不是複製或在寫一個一樣的物件，使用原型繼承。

## \[\[Prototype]]

物件有一個特殊隱藏屬性 \[\[Prototype]]，他指向 null 或者其他物件。從物件讀取物件時，這個屬性會自動消失，取而代之的是指向的原型物件。

![](https://2384301684-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LS3vj0v55HiJ9Pkdigx%2F-LhnV1nMobPnh4beFVjU%2F-LhnWvTalQM1BgCMWabM%2Fobject-prototype-empty%402x.png?alt=media\&token=54f70adc-1b37-49f5-bf33-01b46eeaa5a4)

```javascript
// 設定 [[Prototype]] 的方法
let animal = {
  eats: true
};
let rabbit = {
  jumps: true
};

rabbit.__proto__ = animal;

// __proto__ 是 [[Prototype]] 的訪問函式

// 在 rabbit 找不到的屬性會在 animal 找
let animal = {
  eats: true
};
let rabbit = {
  jumps: true
};

rabbit.__proto__ = animal; // (*)

// we can find both properties in rabbit now:
alert( rabbit.eats ); // true (**)
alert( rabbit.jumps ); // true
```

![](https://2384301684-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LS3vj0v55HiJ9Pkdigx%2F-LhnV1nMobPnh4beFVjU%2F-LhnXpERZnCf4lSU7m9v%2Fproto-animal-rabbit%402x.png?alt=media\&token=61e7341f-5371-4b44-8ff6-2eed97d5e54f)

```javascript
// 在 rabbit 找不到的方法會在 animal 找
let animal = {
  eats: true,
  walk() {
    alert("Animal walk");
  }
};

let rabbit = {
  jumps: true,
  __proto__: animal
};

// walk is taken from the prototype
rabbit.walk(); // Animal walk
```

![](https://2384301684-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LS3vj0v55HiJ9Pkdigx%2F-LhnV1nMobPnh4beFVjU%2F-LhnYKELozG15eBoqehK%2Fproto-animal-rabbit-walk%402x.png?alt=media\&token=da48a095-cce6-4478-b086-14f5ea2dcb84)

```javascript
let animal = {
  eats: true,
  walk() {
    alert("Animal walk");
  }
};

let rabbit = {
  jumps: true,
  __proto__: animal
};

let longEar = {
  earLength: 10,
  __proto__: rabbit
};

// walk is taken from the prototype chain
longEar.walk(); // Animal walk
alert(longEar.jumps); // true (from rabbit)

// 指向不能形成循環會出錯誤
// __proto__ 的值只能是 null 或物件，其他值會被忽略
// 一個物件只能繼承一個物件
```

![](https://2384301684-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LS3vj0v55HiJ9Pkdigx%2F-LhnV1nMobPnh4beFVjU%2F-LhnYhO9my9k8MOqs04N%2Fproto-animal-rabbit-chain%402x.png?alt=media\&token=5edc9534-0052-4899-ad95-fa7843342dde)

## Writing doesn’t use prototype

原型繼承對於資料類型的屬性只能使用 get，無法使用  set，也就是無法更改只能讀取；訪問類型的屬性如果 get、set都有則可以讀取、更改。

```javascript
// data property 不能更改
let animal = {
  eats: true,
  walk() {
    /* this method won't be used by rabbit */
  }
};

let rabbit = {
  __proto__: animal
};

rabbit.walk = function() {
  alert("Rabbit! Bounce-bounce!");
};

rabbit.walk(); // Rabbit! Bounce-bounce!
```

![](https://2384301684-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LS3vj0v55HiJ9Pkdigx%2F-LhnV1nMobPnh4beFVjU%2F-LhnZjJ6TW532d1f7N0S%2Fproto-animal-rabbit-walk-2%402x.png?alt=media\&token=f0a5920a-1e3c-4eb5-a3e4-6d4ed5d2011d)

```javascript
// accessors property 有設置 get、set 可以更改
let user = {
  name: "John",
  surname: "Smith",

  set fullName(value) {
    [this.name, this.surname] = value.split(" ");
  },

  get fullName() {
    return `${this.name} ${this.surname}`;
  }
};

let admin = {
  __proto__: user,
  isAdmin: true
};

alert(admin.fullName); // John Smith (*)

// setter triggers!
admin.fullName = "Alice Cooper"; // (**)
```

## The value of “this”

```javascript
// this 指向使用方法的物件
// animal has methods
let animal = {
  walk() {
    if (!this.isSleeping) {
      alert(`I walk`);
    }
  },
  sleep() {
    this.isSleeping = true;
  }
};

let rabbit = {
  name: "White Rabbit",
  __proto__: animal
};

// modifies rabbit.isSleeping
rabbit.sleep();

alert(rabbit.isSleeping); // true
alert(animal.isSleeping); // undefined (no such property in the prototype)
```

![](https://2384301684-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LS3vj0v55HiJ9Pkdigx%2F-LhnV1nMobPnh4beFVjU%2F-Lhnau4jv9Bch98nEptQ%2Fproto-animal-rabbit-walk-3%402x.png?alt=media\&token=a46d8a50-9cfa-4048-bd6b-abf96c847739)

## for…in loop

```javascript
// for..in 會返回包含原型的屬性
let animal = {
  eats: true
};

let rabbit = {
  jumps: true,
  __proto__: animal
};

// Object.keys only return own keys
alert(Object.keys(rabbit)); // jumps

// for..in loops over both own and inherited keys
for(let prop in rabbit) alert(prop); // jumps, then eats

// 如果不想返回原型的屬性可以用 hasOwnProperty()
let animal = {
  eats: true
};

let rabbit = {
  jumps: true,
  __proto__: animal
};

for(let prop in rabbit) {
  let isOwn = rabbit.hasOwnProperty(prop);

  if (isOwn) {
    alert(`Our: ${prop}`); // Our: jumps
  } else {
    alert(`Inherited: ${prop}`); // Inherited: eats
  }
}
```

![](https://2384301684-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LS3vj0v55HiJ9Pkdigx%2F-LhnV1nMobPnh4beFVjU%2F-Lhnbf2E9SxMA_oRra3e%2Frabbit-animal-object%402x.png?alt=media\&token=542d6264-bfe5-452d-814b-9e7beafe9eaf)
