简体   繁体   中英

Why does the my method in different JS objects produce the same results?

I'm learning Javascript so any help here would be appreciated. In the following code snippet, I created two objects johnTip and markTip that calculate the tip summary of John and Mark. The method tipCalculator is implemented the same way for both objects. However, after calling markTip.calcTip(), I found that tipsJohn would be overriden by tipsMark, ie, they have the same values. Does anyone know what's wrong behind the scene and how to fix this? Thank you.

I've tried switching the order of calling this method on johnTip and markTip but didn't fix the bug.

The expected results would be that tipsJohn and tipsMark are separate objects (arrays). However, it seems like they have the same values after markTip.calcTip was called.

 var johnTip = { bills: [124, 48, 268, 180, 42], calcTip: function() { tips = []; finalBills = []; for (var i = 0; i < this.bills.length; i++) { if (this.bills[i] < 50) { tips[i] = this.bills[i] * 0.2; } else if (this.bills[i] < 200) { tips[i] = this.bills[i] * 0.15; } else { tips[i] = this.bills[i] * 0.1; } finalBills[i] = tips[i] + this.bills[i]; } return [tips, finalBills]; } } var markTip = { bills: [77, 375, 110, 45], calcTip: function() { tips = []; finalBills = []; for (var i = 0; i < this.bills.length; i++) { if (this.bills[i] < 100) { tips[i] = this.bills[i] * 0.2; } else if (this.bills[i] < 300) { tips[i] = this.bills[i] * 0.10; } else { tips[i] = this.bills[i] * 0.25; } finalBills[i] = tips[i] + this.bills[i]; } return [tips, finalBills]; } } let [tipsJohn, finalBillsJohn] = johnTip.calcTip(); let [tipsMark, finalBillsMark] = markTip.calcTip(); console.log('Mark\\'s tip summary: ' + tipsMark); console.log('Mark\\'s final bills paid: ' + finalBillsMark); console.log('John\\'s tip summary: ' + tipsJohn); console.log('John\\'s final bills paid: ' + finalBillsJohn); 

You declared var finalBills; outside declaration of markTip and johnTip. You need to store them in different var .

When you assign a variable without decaling it it has global scope.

x = 5;

Makes a global variable.

let x = 5;

Creates a variable that only has scope to the current block.

Change both of your arrays to

let tips = [];

let finalBills = [];

And they will be different arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM