LeoWangJ / blog

紀錄學習文章
1 stars 0 forks source link

物件導向與構造函數(constructor) #27

Open LeoWangJ opened 4 years ago

LeoWangJ commented 4 years ago

物件導向(Object Oriented Programming 簡稱OOP)的概念是將現實生活中的各種複雜的情況,抽象成各個物件,然後由這些物件進行分工與合作來模擬現實生活的情況。

對於物件的描述

  1. 物件是單個現實例子的抽象
  2. 物件是一個容器,封裝了屬性與方法(function)

例如: 一輛車變成物件的樣子

const car = {
    name: 'toyota',
    color: 'black',
    amount: 700000
    tax: function(countryTax) {
      return  amount * countryTax
   }
}

那我們想要造一台黃色的bmw的車子就必須又要重複定義這個結構

 const bmwCar = {
    name: 'bmw',
    color: 'yellow',
    amount: 1400000
    tax: function(countryTax) {
      return  amount * countryTax
   }
}

那有什麼辦法能夠解決重複結構的問題呢?

構造函數(constructor)使我們不需要再重複定義物件,是製造物件的模板

let Car = function(name,color,amount,countryTax){
    this.name = name
    this.color = color
    this.amount = amount
    this.tax = function(){
        return amount * countryTax
    }
}

構造函數與一般函數來說是沒什麼差別的,只是呼叫方式的不同,構造函數必須使用new來調用一個實例

let toyotaCar = new Car('toyota','black',700000,1.2)