> 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/f.prototype.md).

# F.prototype

```javascript
// 建構函式有 prototype 屬性，可以繼承原型物件
let animal = {
  eats: true
};

function Rabbit(name) {
  this.name = name;
}

Rabbit.prototype = animal; // 當 new Rabbit 被創造 [[Prototype]] 的值為 animal

let rabbit = new Rabbit("White Rabbit"); //  rabbit.__proto__ == animal

alert( rabbit.eats ); // true
```

![](/files/-LhnfGlz-wRrLykh58V8)

## Default F.prototype, constructor property

```javascript
// 每一個函式都有 prototype 屬性，預設為一個物件有 constructor 屬性
function Rabbit() {}

/* default prototype
Rabbit.prototype = { constructor: Rabbit };
*/

// check
function Rabbit() {}
// by default:
// Rabbit.prototype = { constructor: Rabbit }

alert( Rabbit.prototype.constructor == Rabbit ); // true
```

![](/files/-Lhngbk-AGS0UoPPw30P)

```javascript
// 什麼都不做，新的建構函式有 constructor 屬性
function Rabbit() {}
// by default:
// Rabbit.prototype = { constructor: Rabbit }

let rabbit = new Rabbit(); // inherits from {constructor: Rabbit}

alert(rabbit.constructor == Rabbit); // true (from prototype)
```

![](/files/-Lhnh98XTJSE3WZUngRK)

```javascript
// 用 constructor 屬性創造一個跟現有構造函式一樣的物件。
// 當我們有一個物件，但不知道使用哪個構造函式，而我們需要創造一個相似物件時，這個方法很好用。
function Rabbit(name) {
  this.name = name;
  alert(name);
}

let rabbit = new Rabbit("White Rabbit");

let rabbit2 = new rabbit.constructor("Black Rabbit");

// 改變函式的 prototype 屬性，constructor 屬性會消失
function Rabbit() {}
Rabbit.prototype = {
  jumps: true
};

let rabbit = new Rabbit();
alert(rabbit.constructor === Rabbit); // false

// 為了保留 constructor 屬性，可以增加/移除屬性到 prototype 屬性
function Rabbit() {}

// Not overwrite Rabbit.prototype totally
// just add to it
Rabbit.prototype.jumps = true
// the default Rabbit.prototype.constructor is preserved

// 可以手動創造 constructor 屬性
Rabbit.prototype = {
  jumps: true,
  constructor: Rabbit
};

// now constructor is also correct, because we added it
```
