開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- JavaScript (プログラミング言語)
- Safari(Web browser)
Head First JavaScript Programming (Eric T. Freeman (著)、Elisabeth Robson (著)、O'Reilly Media)の Chapter 5.(A trip to Objectville - Understanding Objects)、の EXERCISE(No. 3434)を取り組んでみる。
EXERCISE(No. 3434)
コード(Emacs)
HTML5
<pre id="output0"></pre> <button id="run0">run</button> <button id="clear0">clear</button> <script src="sample8.js"></script>
JavaScript
let btn0 = document.querySelector('#run0'),
btn1 = document.querySelector('#clear0'),
pre0 = document.querySelector('#output0'),
p = (x) => pre0.textContent += x + '\n';
let Car = (make, model, year, color, passengers, convertible, mileage) => {
let that = {},
started = false,
fuel = 0,
start = () => {
if (fuel > 0) {
started = true;
} else {
p('the car is on empty, fill up before starting!');
}
},
stop = () => started = false,
drive = () => {
if (started) {
if (fuel > 0) {
p(`${make} ${model} goes zoom zoom!`);
} else {
p('Uh oh, out of fuel.');
stop();
}
} else {
p('You need to start the engine first.');
}
},
addFuel = (amount) => {
fuel += amount;
};
that.start = start;
that.stop = stop;
that.drive = drive;
that.addFuel = addFuel;
return that;
};
let output = () => {
let fiat = Car('Fiat', '500');
fiat.start();
fiat.drive();
fiat.addFuel(2);
fiat.start();
fiat.drive();
fiat.drive();
fiat.drive();
fiat.stop();
};
btn0.onclick = output;
btn1.onclick = () => pre0.textContent = '';
output();
0 コメント:
コメントを投稿