Rumah >hujung hadapan web >tutorial js >Menggunakan `call`, `apply` dan `bind` dalam Sistem Pengebilan Restoran.
In a restaurant, customers can order multiple dishes, and we want to calculate their total bill based on the prices of the dishes ordered, any applicable taxes, and discounts. We’ll create a function to compute the total bill and use call, apply, and bind to handle different customers and their orders.
// 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
Function Definition:
Customer Objects:
Using call:
Using apply:
Using bind:
This scenario highlights how call, apply, and bind can be utilized in a practical setting, such as calculating restaurant bills, helping to understand how these methods facilitate the management of this in JavaScript.
Atas ialah kandungan terperinci Menggunakan `call`, `apply` dan `bind` dalam Sistem Pengebilan Restoran.. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!