PHP前端开发

在餐厅计费系统中使用“call”、“apply”和“bind”

百变鹏仔 3天前 #JavaScript
文章标签 计费系统

场景概览

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

代码示例

// Function to calculate the total billfunction 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 objectsconst 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 Sarahconst totalBillSarah = calculateTotalBill.call(customer1, 10, 15); // 10% tax and $15 discountconsole.log(`${customer1.name}'s Total Bill: $${totalBillSarah}`); // Output: Sarah's Total Bill: $117// 2. Using `apply` to calculate the total bill for Mikeconst taxRateMike = 8; // 8% taxconst discountMike = 20; // $20 discountconst totalBillMike = calculateTotalBill.apply(customer2, [taxRateMike, discountMike]); // Using apply with an arrayconsole.log(`${customer2.name}'s Total Bill: $${totalBillMike}`); // Output: Mike's Total Bill: $176// 3. Using `bind` to create a function for Sarah's future calculationsconst calculateSarahBill = calculateTotalBill.bind(customer1); // Binding Sarah's contextconst totalBillSarahAfterDiscount = calculateSarahBill(5, 10); // New tax rate and discountconsole.log(`${customer1.name}'s Total Bill after New Discount: $${totalBillSarahAfterDiscount}`); // Output: Sarah's Total Bill after New Discount: $115

解释

  1. 函数定义:

  2. 客户对象:

  3. 使用通话:

  4. 使用 apply:

  5. 使用绑定:

输出

结论

此场景重点介绍了如何在实际设置中使用 call、apply 和 bind,例如计算餐厅账单,有助于理解这些方法如何促进 javascript 中的管理。