{%hackmd BJrTq20hE %} ###### tags: `JaveScript` `核心篇` `class` # class的實戰用法:私有化變數class靜態方法、靜態變數 創造一個class並且寫入class自有方法與變數 ## 私有化變數 就是在class內變數的開頭加入#,私有化變數不會被class以外的方始讀取或式修改 ```javascript= // 創造一個class class Counter{ supFee = 0 extraFee = 0 serviceFee = 0.05 totalFee = 0 // class私有化變數 #shopName = '我的飲料店' constructor(order){ this.list = order this.orderName = this.list[0].name } addPeral(){ this.list.push({name:'加珍珠', price:10}) } countSub(){ this.supFee = this.list.reduce((pre, cur) => {return pre + cur.price},0) } set extraFee(val){ this.extraFee = this.extraFee + val } get extraFee(){ return this.extraFee } countTotal(){ this.countSub() this.totalFee = this.supFee + (this.supFee * this.serviceFee) + this.extraFee } finalOrder(){ this.countTotal() // 使用私有化變數 this.orderName = `${this.#shopName} - ${this.orderName}` } } // 訂單內容 const orderList = [{name:'檸檬紅茶', price:50}] //創造一個訂單實體 ,訂單要在建構式這邊載入,不然新的訂單實體會因會沒有訂單報錯 const myOrder = new Counter(orderList) //加珍珠 myOrder.addPeral() console.log('加珍珠', myOrder.list) // 打破杯子 (寫入額外費用) 使用set所以用賦值的方式寫入 myOrder.extraFee = 20 console.log('額外費用',myOrder.extraFee) // 計算最終價格與寫入私有變數 myOrder.finalOrder() console.log('supFee', myOrder.supFee) console.log('shopName', myOrder.orderName) console.log('totalPrice', myOrder.totalFee) ``` ## class 靜態 class 靜態方法、靜態變數,在不實體化的情況取用class的方法或是變數,有兩點需要注意 1.靜態方法不能調用this 2.不能在實體化使用 ```javascript= class Squar{ // 靜態方法 // 要在函式面前加static static squar(num){ return num * num } //靜態變數 static mySquar = 'mySquar' } // 要如何調用靜態方法、靜態變數? // 直接使用class名稱加.呼叫方法或變數 console.log('Squar',Squar.squar(5)) console.log('SquarVar',Squar.mySquar) ``` [class的實戰用法與class靜態方法、靜態變數](https://codepen.io/efzdamnp-the-lessful/pen/MWVxegE?editors=0011)
×
Sign in
Email
Password
Forgot password
or
By clicking below, you agree to our
terms of service
.
Sign in via Facebook
Sign in via Twitter
Sign in via GitHub
Sign in via Dropbox
Sign in with Wallet
Wallet (
)
Connect another wallet
New to HackMD?
Sign up