開発環境
- macOS Sierra - Apple (OS)
- Emacs (Text Editor)
- JavaScript (プログラミング言語)
- Safari(Web browser)
Head First JavaScript Programming (Eric T. Freeman (著)、Elisabeth Robson (著)、O'Reilly Media)の Chapter 13.(Extra strength objects - Using Prototypes)の CODE MAGNETS(No. 8620)を取り組んでみる。
CODE MAGNETS(No. 8620)
コード(Emacs)
HTML5
<pre id="output0"></pre> <button id="run0">run</button> <button id="clear0">clear</button> <script src="sample5.js"></script>
JavaScript
let btn0 = document.querySelector('#run0'),
btn1 = document.querySelector('#clear0'),
pre0 = document.querySelector('#output0'),
p = (x) => pre0.textContent += x + '\n',
range = (start, end, step=1) => {
let result = [];
for (let i = start; i < end; i += 1) {
result.push(i);
}
return result;
};
let Game = () => {
let that = {},
level = 0,
unlocked = false;
play = () => {
level += 1;
p(`Welcome to level ${level}`);
unlock();
},
unlock = () => {
if (level === 42) {
unlocked = true;
}
};
that.play = play;
that.getLevel = () => level;
that.getUnlocked = () => unlocked;
return that;
};
let Robot = (name, year, owned, game) => {
let that = {},
deployLaser = () => {
if (game.getUnlocked()) {
p(`${name} is blasting you with laser beams.`);
}
},
toString = () =>
`${name} was made by ObjectsRUs in ${year} and is owned by ${owned}`;
that.toString = toString;
that.deployLaser = deployLaser;
return that;
};
let SpaceRobot = (name, year, owned, game, homePlanet) => {
let that = Robot(name, year, owned, game),
speak = () => 'speak',
pilot = () => 'pilot';
that.getHomePlanet = () => homePlanet;
that.speak = speak;
that.pilot = pilot;
return that;
};
let output = () => {
let game = Game(),
robby = Robot('Robby', 1956, 'Dr.Morbius', game),
rosie = Robot('Rosie', 1962, 'George Jetson', game),
robby1 = SpaceRobot('Robby', 1956, 'Dr.Morbius', game, 'homePlanet1'),
rosie1 = SpaceRobot('Rosie', 1962, 'George Jetson', game, 'homePlanet2');
p(robby.getHomePlanet);
p(robby.speak);
p(rosie.pilot);
p(robby1.getHomePlanet());
p(robby1.speak());
p(robby1.pilot());
p(rosie1.getHomePlanet());
p(rosie1.speak());
p(rosie1.pilot());
};
let clear = () => pre0.textContent = '';
btn0.onclick = output;
btn1.onclick = clear;
output();
0 コメント:
コメントを投稿