---
# System prepended metadata

title: 什麼是class?
tags: [核心篇, class, JaveScript]

---

###### tags: `JaveScript` `核心篇` `class`
{%hackmd BJrTq20hE %}

# 什麼是class?
class簡單的來說是繼承與原型練的語法糖
[繼承與原型鍊](https://hackmd.io/nFROdO2PQxKNaCH8iYNg0g)

## 簡單的原型練範例
![](https://i.imgur.com/3NZro3E.png)

```javascript= 
 function Life (){
  this.isLiving = 'live'
}
Life.prototype.breath = function (){
  console.log(this.name+`呼吸`)
}

function Animal (species){
  Life.call(this)
  this.species = 'animal'  
}
Animal.prototype = Object.create(Life.prototype)
Animal.prototype.constructor = Animal
Animal.prototype.move = function (){
  console.log(this.name+`移動`)
}
function Dog(name, color, size){
  Animal.call(this, '犬科')
  this.name = name
  this.color = color
  this.size = size
}
Dog.prototype = Object.create(Animal.prototype)
Dog.prototype.constructor = Dog
Dog.prototype.bark = function(){
  console.log(this.name+ `吼叫`)
}

const dondon = new Dog('dondon', 'black', 'small')
dondon.breath()
dondon.move()
dondon.bark()

function Plant(species){
  Life.call(this)
  this.type = 'plant'
  this.species = species
}
Plant.prototype = Object.create(Life.prototype)
Plant.prototype.constructor = Plant
Plant.prototype.photosynthese = function(){
  console.log(this.name + ` photosynthese`)
}
function Mint(name){
  Plant.call(this, 'mint')
  this.name = name
}
Mint.prototype = Object.create(Plant.prototype)
Mint.prototype.constructor = Mint
Mint.prototype.mintSmell = function(){
  console.log(this.name + ` mintSemll`)
}
const myMint = new Mint('myMint')
console.log(myMint)
myMint.breath()
myMint.photosynthese()
myMint.mintSmell()
```
## 換成class來寫
```javascript=
  // class起手式
  class Life {
  // 建構式，如果要帶入參數在constructor帶入
  constructor(){
    this.isLive = 'live'
  }
  //直接加入方法
  breath(){
    console.log(this.name+ ` breath`)
  }
}
   // 繼承練的寫法加上extends "繼承的class名稱"
class Animal extends Life{
    // Animal所要帶入的參數
  constructor(species){
    // 呼叫上一層的建構式，並帶入參數
    super()
    this.type = 'animal'
    this.species = species
  }
  move(){
    console.log(this.name + ` move`)
  }
}

class Dog extends Animal {
  constructor(name, color, size){
    // 帶入上一層的建構式，並帶入參數
    super('犬科')
    this.name = name
    this.color = color
    this.size = size
  }
  bark(){
    console.log(this.name + ` bark`)
  }
}
const DonDon = new Dog('DonDon', 'Black', 'small')
console.log(DonDon)
DonDon.breath()
DonDon.move()
DonDon.bark()

class Plant extends Life{
  constructor(){
    super()
    this.type = 'planet'
  }
  photosynthese(){
    console.log(this.name + ` photosynthese`)
  }
}

class Mint extends Plant{
  constructor(name){
    super('mint')
    this.name = name
  }
  mintSmell(){
    console.log(this.name + ' mintSmell')
  }
}
const myMint = new Mint('myMint')
console.log(myMint)
myMint.breath()
myMint.photosynthese()
myMint.mintSmell()
```

[基本的建構式與繼承+ class](https://codepen.io/efzdamnp-the-lessful/pen/abYMdVN?editors=0011)
