In einem Restaurant können Kunden mehrere Gerichte bestellen, und wir möchten ihre Gesamtrechnung auf der Grundlage der Preise der bestellten Gerichte, aller anfallenden Steuern und Rabatte berechnen. Wir erstellen eine Funktion zur Berechnung der Gesamtrechnung und verwenden „Call“, „Apply“ und „Bind“, um verschiedene Kunden und deren Bestellungen zu bearbeiten.
// 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
Funktionsdefinition:
Kundenobjekte:
Mit Aufruf:
Verwenden von apply:
Verwenden von bind:
Dieses Szenario zeigt, wie Call, Apply und Bind in einer praktischen Umgebung verwendet werden können, beispielsweise bei der Berechnung von Restaurantrechnungen, und hilft zu verstehen, wie diese Methoden die Verwaltung dieser Aufgaben in JavaScript erleichtern.
Haftungsausschluss: Alle bereitgestellten Ressourcen stammen teilweise aus dem Internet. Wenn eine Verletzung Ihres Urheberrechts oder anderer Rechte und Interessen vorliegt, erläutern Sie bitte die detaillierten Gründe und legen Sie einen Nachweis des Urheberrechts oder Ihrer Rechte und Interessen vor und senden Sie ihn dann an die E-Mail-Adresse: [email protected] Wir werden die Angelegenheit so schnell wie möglich für Sie erledigen.
Copyright© 2022 湘ICP备2022001581号-3