Javascript麻瓜: 便利商店買東西,零錢夠不夠
For Javascript Muggle: Are your changes enough for buying a good in convenience store (exercise and codes sample)
Please
apply what you have learned from the following pages to check if you
have enough changes in your pocket to buy a good in a convenience store.
name of good
|
cost to buy
|
pennies ($0.01)
|
nickels
($0.05)
|
dimes
($0.1)
|
quarters
($0.25)
|
a
|
$3
|
6
|
25
|
30
|
10
|
b
|
$10
|
0
|
24
|
15
|
3
|
c
|
$25
|
3
|
85
|
1
|
150
|
d
|
$15
|
20
|
0
|
250
|
48
|
e
|
$8
|
35
|
37
|
1
|
5
|
Your codes should be able to print the following output to the console:
- Good name: a, Cost: 3, Buy? YES
- Good name: b, Cost: 10, Buy? NO
- Good name: c, Cost: 25, Buy? YES
- Good name: d, Cost: 15, Buy? YES
- Good name: e, Cost: 8, Buy? NO
-
Thefollowing sample codes has applied "Object Oriented Javascript', "Inheritance', and 'Function Context'.
let Pocket=function(){};
Pocket.prototype.initialize = function (penny, nickel, dime, quarter)
{
this.penny=0.01*penny;
this.nickel=0.05*nickel;
this.dime=0.2*dime;
this.quarter=0.25*quarter;
this.changestotal=this.penny+this.nickel+this.dime+this.quarter;
};
let CheckEnoughChanges = function(){};
CheckEnoughChanges.prototype = new Pocket();
CheckEnoughChanges.prototype.good = function(name, cost)
{
this.goodName=name;
this.goodCost=cost;
};
let good = new CheckEnoughChanges();
var boundCompareCost=compareCost.bind(good);
function compareCost()
{
if (this.changestotal >= this.goodCost) console.log('Good name: '+this.goodName+', '+'Cost: '+this.goodCost+', '+'Buy? '+'YES');
else console.log('Good name: '+this.goodName+', '+'Cost: '+this.goodCost+', '+'Buy? '+'NO');
};
good.initialize(6,25,30,10);
good.good('a', 3);
boundCompareCost();
good.initialize(0,24,15,3);
good.good('b', 10);
boundCompareCost();
good.initialize(3,85,1,150);
good.good('c', 25);
boundCompareCost();
good.initialize(20,0,250,48);
good.good('d', 15);
boundCompareCost();
good.initialize(35,37,1,5);
good.good('e', 8);
boundCompareCost();
留言