Как правильно написать конструктор?
Подскажите, как правильно написать конструктор, который будет создавать новые объекты и div`ы в разметке. Как правильно связать созданный объект и div?
function Unit(name,life,monsterLeft,monsterBottom) {
this.name = document.createElement('div');
this.className = "monster";
this.style.left= monsterLeft + "px";
this.style.bottom= monsterBottom + "px";
this.life = life;
game.append(this);
this.botRightXDistance = 10;
this.botLeftXDistance = -10;
this.botDownYDistance = -10;
this.botUpYDistance = 10;
}
Ответы (1 шт):
Автор решения: OPTIMUS PRIME
→ Ссылка
Внутри конструктора, this ссылается на текущий создаваемый объект. Но никто не мешает внутри объекта - делать другой объект, или записать let div = document.createElement('div'); this.html = div; и обращаться к элементу через переменную div.style...
*this.botRightXDistance - у вас 4 раза повторяются названия, что намекает, что их можно сгруппировать в отдельный объект (или, как минимум, подумать об этом).
const units = {};
const game = {
append: function(unit) {
document.body.appendChild( unit.node );
units[ unit.id ] = unit;
}
};
Unit.created = 0;
function Unit(obj = {}) {
this.node = document.createElement('div');
this.node.className = "monster";
this.node.style.left = obj.left + "px";
this.node.style.bottom = obj.bottom + "px";
this.node.textContent = "•\\_/•";
this.id = Unit.created++;
this.name = obj.name || "bot_" + Unit.created;
this.life = obj.life || 1000;
this.bot_distance = {
right_x: 10,
left_x: -10,
down_y: -10,
up_y: 10,
};
game.append(this);
}
new Unit({life: 2000, left: 100, bottom: 70});
new Unit({life: 2000, left: 180, bottom: 30});
.monster {
position: absolute;
width: 50px;
height: 50px;
border-radius: 50%;
background: orange;
text-align: center;
line-height: 0;
padding-top: 25px;
box-sizing: border-box;
}