Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
LeoWangJ opened this issue Mar 19, 2020 · 0 comments
Open

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

LeoWangJ opened this issue Mar 19, 2020 · 0 comments
Labels
JS js knowledge

Comments

@LeoWangJ
Copy link
Owner

物件導向(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)
@LeoWangJ LeoWangJ added the JS js knowledge label Mar 19, 2020
This was referenced Mar 26, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
JS js knowledge
Projects
None yet
Development

No branches or pull requests

1 participant