레스토랑 청구 시스템에서 `call`, `apply` 및 `bind` 사용

Mary-Kate Olsen
풀어 주다: 2024-09-26 17:36:02
원래의
375명이 탐색했습니다.

Using `call`, `apply`, and `bind` in a Restaurant Billing System.

Scenario Overview

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.

Code Example

// 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
로그인 후 복사

Explanation

  1. Function Definition:

    • We define a function calculateTotalBill that takes taxRate and discount as parameters. This function calculates the total bill by adding tax to the order total and subtracting any discounts.
  2. Customer Objects:

    • We create two customer objects, customer1 (Sarah) and customer2 (Mike), each with their respective names and total order amounts.
  3. Using call:

    • For Sarah, we calculate her total bill using the call method. This allows us to specify customer1 as the context and pass the tax rate and discount as separate arguments. The output shows Sarah's total bill after applying the tax and discount.
  4. Using apply:

    • For Mike, we use the apply method to calculate his total bill. This method allows us to pass the parameters as an array, making it convenient for handling multiple arguments. The total bill for Mike is calculated similarly but with different tax and discount values.
  5. Using bind:

    • We create a bound function for Sarah using bind, which locks the context to customer1. This means we can later call this new function without needing to specify this again. We demonstrate this by calculating Sarah's total bill again with different parameters, allowing for flexible future calculations.

Output

  • The console logs display the total bills for both Sarah and Mike based on their respective orders and discounts.
  • This example effectively demonstrates how call, apply, and bind can be used to manage function contexts within a restaurant billing system.

Conclusion

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.

위 내용은 레스토랑 청구 시스템에서 `call`, `apply` 및 `bind` 사용의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!