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