как можно добавить id в конструктор? html:
<div id="elem"></div>
js:
function ready() {
function Rectangle(i, w, h, c) {
this.id = i;
this.width = w;
this.height = h;
this.color = c;
}
Rectangle.prototype.elemId = function() {
return this.id = document.getElementById();
}
Rectangle.prototype.doublewidth = function() {
return this.width * 2;
}
Rectangle.prototype.doubleheight = function() {
return this.height * 2;
}
var oneRect = new Rectangle("elem", 300, 150, "green");
oneRect.elemId().style.background = oneRect.color;
oneRect.elemId().style.width = oneRect.doublewidth() + "px";
oneRect.elemId().style.height = oneRect.doubleheight() + "px";
};
document.addEventListener("DOMContentLoaded", ready);
Судя по всему, вы пытаетесь вернуть элемент по id в методе elemId:
Rectangle.prototype.elemId = function() {
return document.getElementById(this.id);
}
В том же конструкторе можете создать поле, где будет храниться ссылка на html-объект, потому что каждый раз вызывать getElementById не очень правильно
function ready() {
function Rectangle(i, w, h, c) {
this.id = i;
this.width = w;
this.height = h;
this.color = c;
// ссылка на html объект
this.elem = document.getElementById(i);
}
Rectangle.prototype.doublewidth = function() {
return this.width * 2;
}
Rectangle.prototype.doubleheight = function() {
return this.height * 2;
}
var oneRect = new Rectangle("elem", 300, 150, "green");
oneRect.elem.style.background = oneRect.color;
oneRect.elem.style.width = oneRect.doublewidth() + "px";
oneRect.elem.style.height = oneRect.doubleheight() + "px";
};
document.addEventListener("DOMContentLoaded", ready);
Пример реализации через сеттеры(описал только ширину для простоты):
function Rectangle(id, w, h, color) {
var el = document.getElementById(id);
el.style.width = w + 'px';
el.style.height = h + 'px';
el.style.backgroundColor = color;
return {
set width(width) {
w = width;
el.style.width = w + 'px';
},
get width() {return w;}
};
}
var r = new Rectangle('rect', 25, 50, 'red');
setTimeout(() => r.width*=2, 500);
<div id="rect"></div>
Продвижение своими сайтами как стратегия роста и независимости