在餐廳中,顧客可以點多種菜餚,我們希望根據所點菜餚的價格、任何適用的稅費和折扣來計算他們的總帳單。我們將建立一個函數來計算總帳單,並使用呼叫、應用和綁定來處理不同的客戶及其訂單。
// Function to calculate the total bill function calculateTotalBill(taxRate, discount) { const taxAmount = this.orderTotal * (taxRate / 100); // Calculate tax based on the total order amount const totalBill = this.orderTotal taxAmount - discount; // Calculate the final bill return totalBill; } // Customer objects const customer1 = { name: "Sarah", orderTotal: 120 // Total order amount for Sarah }; const customer2 = { name: "Mike", orderTotal: 200 // Total order amount for Mike }; // 1. Using `call` to calculate the total bill for Sarah const totalBillSarah = calculateTotalBill.call(customer1, 10, 15); // 10% tax and $15 discount console.log(`${customer1.name}'s Total Bill: $${totalBillSarah}`); // Output: Sarah's Total Bill: $117 // 2. Using `apply` to calculate the total bill for Mike const taxRateMike = 8; // 8% tax const discountMike = 20; // $20 discount const totalBillMike = calculateTotalBill.apply(customer2, [taxRateMike, discountMike]); // Using apply with an array console.log(`${customer2.name}'s Total Bill: $${totalBillMike}`); // Output: Mike's Total Bill: $176 // 3. Using `bind` to create a function for Sarah's future calculations const calculateSarahBill = calculateTotalBill.bind(customer1); // Binding Sarah's context const totalBillSarahAfterDiscount = calculateSarahBill(5, 10); // New tax rate and discount console.log(`${customer1.name}'s Total Bill after New Discount: $${totalBillSarahAfterDiscount}`); // Output: Sarah's Total Bill after New Discount: $115
函數定義:
顧客對象:
使用呼叫:
使用 apply:
使用綁定:
此場景重點介紹如何在實際設定中使用 call、apply 和 bind,例如計算餐廳帳單,有助於理解這些方法如何促進 JavaScript 中的管理。
免責聲明: 提供的所有資源部分來自互聯網,如果有侵犯您的版權或其他權益,請說明詳細緣由並提供版權或權益證明然後發到郵箱:[email protected] 我們會在第一時間內為您處理。
Copyright© 2022 湘ICP备2022001581号-3