在餐厅,顾客可以点多道菜,我们希望根据所点菜的价格、任何适用的税费和折扣来计算他们的总账单。我们将创建一个函数来计算总账单,并使用调用、应用和绑定来处理不同的客户及其订单。
// 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(null, 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 中的管理。