I have some problem with classes in es6. Me need auto increment id value each time I'm creating objects. Really don't understand how I can declare variable, assign value to _id and then increment increment variable.
class Rectangle {
constructor(name,width,height,x,y) {
if (typeof(name) === 'string' && typeof(width,height,x,y) === 'number' ) {
this._id = ?;
this._name = name;
this._width = width;
this._height = height;
this._x = x;
this._y = y;
var div = document.createElement("div");
document.body.appendChild(div);
div.id = this._id;
div.style.width = this._width + "px";
div.style.height = this._height + "px";
div.style.backgroundColor = "#ededed";
div.innerHTML = name;
}
else {
alert("No way!");
return false;
}
}
moveObj(dx,dy) {
this._x = this._x + dx
this._y = this._y + dy
console.log(this._x,this._y)
return this;
}
getCoords() {
let x = this._x;
let y = this._y;
return [x,y];
}
}
Just add a ID generator as a static method in the Rectangle class:
class Rectangle {
constructor() {
this._id = Rectangle.incrementId()
}
static incrementId() {
if (!this.latestId) this.latestId = 1
else this.latestId++
return this.latestId
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With