はじめに
こんにちは!@70days_jsです。
昨日覚えたオブジェクト(プロトタイプベース)の復習をしました。
59日目。(2019/12/16)
よろしくお願いします。
サイトURL
やったこと
オブジェクト(プロトタイプベース)の復習です。
男性用の名前、女性用の名前のデータを用意しておくと、ランダムでオブジェクトを生成してくれます。
(リロードごとにランダムに表示されている)
html↓
<body></body>
css↓
.page {
display: inline-block;
width: 200px;
height: 200px;
background-color: red;
margin: 30px 10px 10px 10px;
}
JavaScript(72行あります)↓
let canvas = document.getElementById("canvas"),
order = 0,
humanName = [["men1", "men2", "men3"], ["women1", "women2", "women3"]],
men = humanName[0].length,
woman = humanName[1].length,
num = men + woman,
hairetu = [],
menOrwoman = ["men", "woman"];
function Human(id, sex, name) {
this.initialize(id, sex, name);
}
Human.prototype.greet = function() {
let idDiv = document.getElementById(this.id);
idDiv.innerHTML =
"Hello, I'm " +
this.name +
"<br>My sex is " +
this.sex +
"<br>id is " +
this.id;
if (this.sex === "men") {
idDiv.style.backgroundColor = "blue";
}
};
function render() {
hairetu.forEach(function(object) {
object.greet();
});
}
Human.prototype.initialize = function(id, sex, name) {
this.sex = menOrwoman[sex];
this.id = id;
this.name = name;
};
function createHuman() {
let id = order;
let sex;
if (men <= 0) {
sex = 1;
woman--;
} else if (woman <= 0) {
sex = 0;
men--;
} else {
sex = Math.round(Math.random());
if (sex === 0) men--;
if (sex === 1) woman--;
}
let number;
if (menOrwoman[sex] === "men") number = Math.floor(Math.random() * men);
if (menOrwoman[sex] === "woman") number = Math.floor(Math.random() * woman);
let name = humanName[sex][number];
humanName[sex].splice(number, 1);
let human = new Human(id, sex, name);
hairetu.push(human);
let div = document.createElement("div");
div.setAttribute("class", "page");
div.setAttribute("id", order);
order++;
document.body.appendChild(div);
}
for (var i = 0; i < num; i++) {
createHuman();
}
render();
ポイントはコンストラクターを用意して、initializeで初期値を入れて、好きなメソッドをprototypeを通して入れるということです。
コンストラクター↓
function Human(id, sex, name) {
this.initialize(id, sex, name);
}
initialize↓
Human.prototype.initialize = function(id, sex, name) {
this.sex = menOrwoman[sex];
this.id = id;
this.name = name;
};
メソッド↓
Human.prototype.greet = function() {
...
}
今回男女の名前は、多次元配列に入れています。↓
humanName = [["men1", "men2", "men3"], ["women1", "women2", "women3"]]
humanName[0]が男で、humanName[1]が女です。
ここに好きな名前を入れていくと、リロード時にランダムでそれぞれの名前のオブジェクトを生成してくれます。
感想
年末までにインベーダーゲームとオセロを仕上げたいですね。
オブジェクト指向が習得できればできるような気がする...かも。
最後まで読んでいただきありがとうございます。明日も投稿しますのでよろしくお願いします。